简体   繁体   中英

Url rewrite with regular expression not working

I have this RewriteRule code on my /etc/apache2/apache2.conf file.

<Directory /var/www/html/demo/>
    # New URL Structure
    RewriteEngine On
    Allow From All
    RewriteBase /

    RewriteRule "^page/(([A-Za-z0-9\-]+/)*[A-Za-z0-9\-]+)/(.*)$" detail.php?url=$1 [L]
</Directory>

I have this URL: http://example.com/page/parameter-1/parameter-2 and RewriteRule is working perfect but when I try with this URL http://example.com/page/parameter-1 it is not working.

http://example.com/page/parameter-1 [Not working]
http://example.com/page/parameter-1/parameter-2 [Working]
http://example.com/page/parameter-1/parameter-2/parameter-3 [Working]

Any idea what I am doing wrong?

Thanks.

That is because of your regex pattern which is always assuming there is a / always after page/ .

You can simplify this to:

<Directory /var/www/html/demo/>
    # New URL Structure
    RewriteEngine On
    Allow From All
    RewriteBase /

    RewriteRule ^/?page/([a-z].*)$ detail.php?url=$1 [L,QSA,NC]

</Directory>

Okay, lets break down what your regex matches:

^page/ - Your URL must start with "page/", all good so far.

(([A-Za-z0-9\\-]+/)* - Your URL can have 0 or more segments in it.

[A-Za-z0-9\\-]+)/(.*)$ - Your URL must end with some segment, followed by a slash, followed by anything

This last part is where the regex goes a bit wrong. Your first example does not have a slash after "page/".

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