清洁URL和PHP文件扩展名除去
我想用.htaccess
来实现两件事:
- slug”中显示值
- 仅在URL参数“ “只需删除文件扩展名” .php。
我有以下.htaccess
代码,该代码在上面处理第1点:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ somepage.php?slug=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ somepage.php?slug=$1
问题是;如何将上面的点2合并到相同的代码中,而不会破坏第一点中已经有效的内容?
我尝试简单地将以下代码包括以下代码,但是当我转到example.com/somepage
时,这给了我404的错误:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
I want to achieve two things with .htaccess
:
- Only show the value in the URL parameter "slug" making the URL clean
- For all other php pages on my site which doesn't have the URL parameter "slug" simply remove the file extension ".php".
I have the following .htaccess
code which takes care of point 1 above:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ somepage.php?slug=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ somepage.php?slug=$1
The question is; how do I incorporate point 2 above in the same code without breaking what is already working in point one?
I have tried simply including the following code below the above but this gives me a 404 error when I go to example.com/somepage
:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要优先考虑扩展的
.php
url,因此此规则需要在重写“ slug”的现有规则之前 。您还需要在重写请求之前检查是否存在相应的
.php
文件。您当前建议的规则盲目地重写请求时,当请求不是映射到文件时,这自然会捕获应捕获的请求,否则应将其重写为“ slug”。反试试它(在root
.htaccess
file中):我将您的两个规则组合为将“ slug”重写为一个规则,因为唯一的区别是拖延斜线 - 只需使其可选在正则。
\ w
速记字符类,与[A-ZA-Z0-9 _]
相同。但是,考虑规范化尾斜线(即重定向到一个或另一个)。因为允许可选的拖尾斜线(两个不同的URL)提供与可能创建重复的内容问题相同的内容。错误SomePage ,所以我认为它一定是
somepage.php
生成404响应而不是Apache?You need to prioritise your extensionless
.php
URLs, so this rule needs to go before your existing rule that rewrites the "slug".You also need to check that the corresponding
.php
file exists before rewriting the request. The rule you are currently proposing blindly rewrites the request when the request does not map to a file, so this would naturally catch requests that should otherwise be rewritten to the "slug".Try it like this instead (in the root
.htaccess
file):I've combined your two rules that rewrite to "slug" into one, since the only difference is the trailing slash - just make it optional in the regex. The
\w
shorthand character class in the same as[a-zA-Z0-9_]
. HOWEVER, consider canonicalising the trailing slash instead (ie. redirect to one or the other). Since by allowing an optional trailing slash (two different URLs) to serve the same content you are potentially creating a duplicate content issue.The request would have been rewritten to
somepage.php?slug=somepage
, so I assume it must have beensomepage.php
that generated the 404 response, rather than Apache?