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 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点