douqian8238 2014-05-05 18:15
浏览 21
已采纳

使用htaccess和PHP清理URL

I've done the due diligence, spending hours poring through searches and stack QA. No dice. So I finally come here to request help.

  • Apache HTTP Server
  • PHP 5.3

I have dirty urls:

.cc/store/index.php?route=checkout/cart
.cc/store/index.php?route=common/home
.cc/store/index.php?route=product/product&product_id=111

I'd like to clean them so when a user clicks on a dirty link or types a dirty url they get a clean url in the address bar:

.cc/store/cart
.cc/store/home
.cc/store/product/11

Currently I have my htaccess file in:

.cc/store/.htaccess

I know I need in htaccess:

RewriteEngine On

But is this the right path?:

RewriteRule !/index.php?route=(A-Z)/(A-Z)&(*)$ /$2/$3

Q1: Do I need to just edit the htaccess file or will I also have to write some php?

Q2: What htaccess / php code do I write to get the desired clean urls? I want to see clean urls in the address bar of my browser.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dshmvqnl98119 2014-05-05 19:46
    关注

    This:

    RewriteRule !/index.php?route=(A-Z)/(A-Z)&(*)$ /$2/$3
    

    Isn't what you want. You're going to need 2 types of rules, ones that externally redirect the browser to the URL that you want to see, then ones that internally rewrite to the URL that your system can understand (the "dirty" ones). So something like:

    RewriteEngine On
    RewriteBase /store/
    
    RewriteCond %{THE_REQUEST} \ /+store/index\.php\?route=checkout/cart
    RewriteRule ^ /store/cart? [L,R]
    
    RewriteCond %{THE_REQUEST} \ /+store/index\.php\?route=common/home
    RewriteRule ^ /store/home? [L,R]
    
    RewriteCond %{THE_REQUEST} \ /+store/index\.php\?route=product/product&product_id=([^&\ ]+)
    RewriteRule ^ /store/product/%1? [L,R]
    
    RewriteRule ^cart$ index.php?route=checkout/cart [L,QSA]
    RewriteRule ^home$ index.php?route=common/home [L,QSA]
    RewriteRule ^product/(.+)$ index.php?route=product/product&product_id=$1 [L,QSA]
    

    You can't make it "wildcard" like matching because you're changing something like "X/Y" to just "Y", which means when you internally rewrite it back, the "X" part is lost forever.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)