简体   繁体   English

htaccess中的RewriteRule错误

[英]RewriteRule error in the htaccess

I have a problem which is as follows: 我有一个如下问题:

RewriteRule ^site   site.php [NC,L]
RewriteRule ^site/([0-9a-zA-Z_-]+)$ site.php?parameter=1$ [NC,L]

The idea is to recognize that if there is a parameter in the url. 这个想法是要认识到url中是否有参数。 So that's what I want: 这就是我想要的:

www.example.com/site
www.example.com/site/1

According to my knowledge, but I simply was trying things didn't work out. 据我所知,但我只是在尝试无法解决问题。 Thank you in advance. 先感谢您。

In your pair of rules the first one will match both example URLs. 在您的规则对中,第一个将与两个示例URL匹配。 So the second rule will never get applied. 因此,第二条规则将永远不会得到应用。 You have to change the order of the rules: 您必须更改规则的顺序:

RewriteEngine on
RewriteRule ^/?site/([0-9a-zA-Z_-]+)$ site.php?parameter=$1 [NC,L]
RewriteRule ^/?site/?$ site.php [NC,L]

Note that I also modified the now second rule slightly to prevent it matching paths like /sitelist for example. 请注意,我还稍微修改了第二条规则,以防止它与/sitelist类的路径匹配。 Also it prevents a redirection loop because of matching /site.php too... The initial /? 同样,它也因为匹配/site.php而防止了重定向循环/? I also added allows to use the same rules in the http servers host configuration without modification, not only in .htaccess style dynamic configuration files. 我还添加了允许在http服务器主机配置中使用相同规则而无需进行修改的方法,不仅限于.htaccess样式的动态配置文件。

A general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (" .htaccess "). 一个一般提示:您应该始终喜欢将此类规则放置在http服务器主机配置中,而不是使用动态配置文件(“ .htaccess ”)。 Those files are notoriously error prone, hard to debug and they really slow down the server. 众所周知,这些文件容易出错,难以调试,并且确实降低了服务器的速度。 They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare). 仅当您无法控制主机配置(阅读:真正便宜的托管服务提供商)或者您的应用程序依赖于编写自己的重写规则(这显然是安全噩梦)时,才提供它们作为最后的选择。 )。

This line will redirect any URL that begins with site to site.php: 此行会将以site开头的所有URL重定向到site.php:

RewriteRule ^site   site.php [NC,L]

This line will never run because site was already caught and redirected by the first rule: 此行将永远不会运行,因为site已被第一条规则捕获并重定向:

RewriteRule ^site/([0-9a-zA-Z_-]+)$ site.php?parameter=$1 [NC,L]

So simply running the second rule first will resolve the issue as it will trigger the more specific case. 因此,只需先运行第二条规则即可解决该问题,因为它将触发更具体的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM