【问题标题】:Clean URL with htaccess and PHP使用 htaccess 和 PHP 清理 URL
【发布时间】:2014-06-22 03:25:42
【问题描述】:

我已经完成了尽职调查,花费数小时仔细研究搜索和堆栈 QA。没有骰子。所以我终于来这里寻求帮助了。

  • Apache HTTP 服务器
  • PHP 5.3

我的网址很脏:

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

我想清理它们,这样当用户点击脏链接或输入脏网址时,他们会在地址栏中得到一个干净的网址:

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

目前我的 htaccess 文件位于:

.cc/store/.htaccess

我知道我需要在 htaccess 中:

RewriteEngine On

但这是正确的道路吗?:

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

Q1:我只需要编辑 htaccess 文件还是我还必须编写一些 php?

Q2:我要编写什么 htaccess / php 代码来获得所需的干净 url?我想在浏览器的地址栏中看到干净的 url。

提前致谢。

【问题讨论】:

    标签: php apache .htaccess url clean-urls


    【解决方案1】:

    无论是 PHP 还是简单的 HTML 生成这些 URL,都需要更新以包含新的 URL。 mod_rewrite 简单地获取“干净” url 并将其转换为原始“脏” url,这样您的原始代码仍然可以使用相同的参数运行。

    【讨论】:

    • 实际上并非如此:您可以通过进行外部重定向来为此目的使用重写模块。虽然我同意很可能不是在寻找这样的解决方案。
    • 啊,所以另一种方法是编辑链接生成器(在 html/php 中)以生成干净的 url,然后用户会看到这些干净的 url,而 htaccess 会将干净的 url 转换为脏的服务器进程(即服务器输出干净的 url,用户看到干净的 url,服务器脏 url,服务器处理脏 url)。酷!
    【解决方案2】:

    这个:

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

    这不是你想要的。您将需要 2 种类型的规则,一种是在外部将浏览器重定向到您想要查看的 URL,另一种是在内部重写为您的系统可以理解的 URL(“脏”的)。所以像:

    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]
    

    您不能像匹配一样将其设为“通配符”,因为您将“X/Y”之类的内容更改为“Y”,这意味着当您在内部将其重写时,“X”部分将永远丢失。

    【讨论】:

    • 成功了!我会将此语法扩展到其他页面以进行 url 清理。外部/内部重定向概念也很有意义!非常感谢!
    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多