php.htaccessurlvanity-url

HTACCESS | Adding a second rewrite rule?


I'm trying to write my .htaccess to support two vanity url's, the code will speak for itself as I'm not very good with .htaccess.

 RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?p=$1&s=$2 [L,QSA]

Upon going to for example http://website.com/home/test

I get a 404, but $_GET["p"] still returns back home if I go to just website.com/home.

Why am I getting a 404 when adding in my second variable in the url?


Solution

  • You get a 404 because /home/test does not match the expression ^[a-zA-Z0-9]+/?$. The second group after the first / exists beyond your $ string terminator. You need to add a second () group, which is optional. I have replaced the a-zA-Z0-9 character classes with [^/]+ which matches everything up to the next slash.

    The (?:) indicates a non-capturing group encompasing the first /, with a capturing group () inside it to retrieve the $2 component. The entire construct is made optional with ? before the final $ terminator.

    RewriteEngine On
    RewriteRule ^([^/]+)(?:/([^/]+)/?)?$ index.php?p=$1&s=$2 [L,QSA]