Search code examples
regex.htaccessmod-rewriteurl-rewriting

Mod rewrite rule for optional language in URL


I have a shop URL like this

https://domain.eu/cz/lp/9200

And I'm trying to rewrite it in .htaccess to https://domain.eu/lp/index.php?id=$2&lang=$1

I came really close with

RewriteRule ^/?(hr|sk|pl|cz|ro|it)/lp/(\d+)?$ /lp/index.php?id=$2&lang=$1

which works ok but I can't seem to find a way to handle the situation when there is no lang in URL.

So this is also valid: https://domain.eu/lp/9200 but in that case I want $1 to just be empty (or have a default value when it's not present)

I know "?" means "one or zero" times that's why I tried

RewriteRule ^/?[(hr|sk|pl|cz|ro|it)?]/lp/(\d+)?$ /lp/index.php?id=$2&lang=$1

But it doesn't work as expected. Any point in the right direction would be appreciated.


Solution

  • With your shown samples, attempts; please have your htaccess Rules file in following manner. Make sure to clear your browser cache before testing your URLs.

    RewriteEngine ON
    ##Rewrite rule for uris which have only 1 parameter.
    RewriteRule ^lp/(\d+)/?$ /lp/index.php?id=$1 [NC,L]
    ##Rewrite rule for uris which 2 parameters.
    RewriteRule ^(hr|sk|pl|cz|ro|it)/lp/(\d+)/?$ /lp/index.php?id=$2&lang=$1 [NC,L]
    


    OR use following solutions, in case uris you are trying to access are non-existent ones. Make sure either use 1st solution OR this one, once at a time only.

    RewriteEngine ON
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^lp/(\d+)/?$ /lp/index.php?id=$1 [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(hr|sk|pl|cz|ro|it)/lp/(\d+)/?$ /lp/index.php?id=$2&lang=$1 [NC,L]