【问题标题】:Use mod_rewrite to remove .php extension and clean GET urls concurrently使用 mod_rewrite 删除 .php 扩展名并同时清理 GET url
【发布时间】:2013-11-19 20:40:55
【问题描述】:

这是我到目前为止所尝试的:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]

RewriteCond %{QUERY_STRING} ^id=([0-9]{1})$
RewriteRule ^article\.php$ /article/%1 [L]

基本上,第一组规则将 URL 从 something.php 转换为 something。

第二组规则应该将其中包含 article.php?id=NUMBER 的任何内容替换为 /article/NUMBER。

Apache 报告:

AH00124: Request exceeded the limit of 10 internal redirects due to probable 
configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary.

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

    The second set of rules is supposed to replace anything that has article.php?id=NUMBER in it into /article/NUMBER.

    我相信你的规则颠倒了。

    试试这个代码:

    RewriteEngine On
    RewriteBase /mellori/
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} /article\.php\?id=([^\s&]+) [NC]
    RewriteRule ^ article/%1? [R=302,L]
    
    # internally rewrites /article/123 to article.php?id=123
    RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L,NC,QSA]
    
    # PHP hiding rule
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*)$ $1.php [L]
    

    【讨论】:

    • 这种工作......但不完全......请求:http://localhost/mellori/article.php?id=33 并得到http://localhost/opt/lampp/htdocs/mellori/article/33,这是我系统中的完整路径,而不是来自 webroot(因此它会导致找不到对象错误)
    • 这个 .htaccess 是位于 DOCUMENT_ROOT 还是某个子目录?
    • webroot 位于 /opt/lampp/htdocs/,.htaccess 位于 /opt/lampp/htdocs/mellori
    • 这似乎对我很有效。但是,如何修改它以同时处理 http://localhost/opt/lampp/htdocs/mellori/article/33http://localhost/opt/lampp/htdocs/mellori/article/33/(请注意尾随 /
    • 在此处设置斜杠可选:RewriteRule ^article/([0-9]+)/?$
    【解决方案2】:

    当您匹配^article\.php$ 时,您需要确保它来自实际请求,而不是由先前规则重写的 URI。因此,您可以为内部重定向附加 ENV 检查,或匹配 `%{THE_REQUEST}。

    您的选择:

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{QUERY_STRING} ^id=([0-9]{1})$
    RewriteRule ^article\.php$ /article/%1 [L]
    

    RewriteCond %{THE_REQUEST} \ /+article\.php\?id=([0-9]{1})(\ |$)
    RewriteRule ^ /article/%1 [L]
    

    【讨论】:

    • 不...我仍然遇到重定向问题。这是我完整的 .htaccess 文件,没有作为错误(404、403 等)处理程序工作的文档:paste.ubuntu.com/6386963 当然我在编辑文件后重新启动了 apache,请注意 article.php 文件位于 webroot 的子目录下(我们称它为“子目录”),如果这与...有关...
    猜你喜欢
    • 2013-04-20
    • 2012-08-27
    • 2013-10-11
    • 2015-06-29
    • 1970-01-01
    • 2014-01-25
    • 2020-08-11
    • 2012-08-27
    相关资源
    最近更新 更多