简体   繁体   中英

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. 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. 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. Also it prevents a redirection loop because of matching /site.php too... The initial /? 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.

A general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (" .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:

RewriteRule ^site   site.php [NC,L]

This line will never run because site was already caught and redirected by the first rule:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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