Search code examples
apache.htaccessmod-rewrite

htaccess RewriteRule - how to replace get parameter to &


I know that there are many post in here about RewriteRule regex question, but my one is difference. I follow this tutorial (https://www.visualscope.com/seo-friendly-urls.html) to make a seo friendly url and it work except when user change language.

URL (this works):

/wedding-venue-details/abc-hotel/ -> /wedding-venue-details/?seoURL=abc-hotel

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^wedding-venue-details/(.*)$ ./wedding-venue-details/?seoURL=$1
</IfModule>

but if the user tries to change the language in this page, the URL will become:

/wedding-venue-details/abc-hotel/?lang=en

I just don't know how to replace ?lang=en to &lang=en and append to the end, I tried but still can't get it work.


Solution

  • RewriteRule ^wedding-venue-details/(.*)$ ./wedding-venue-details/?seoURL=$1
    

    You need to use the QSA (Query String Append) flag to append the lang=en parameter onto the end of the query string on the rewritten URL. Apache then handles the merging of the URL parameters and correctly formats the query string.

    You are also missing the L flag (important if you add any more directives).

    For example:

    RewriteRule ^wedding-venue-details/(.*) wedding-venue-details/?seoURL=$1 [QSA,L]
    

    You should remove the ./ prefix from the substitution string (it has no place here - get gets resolved away later).

    This will rewrite /wedding-venue-details/abc-hotel/?lang=en to /wedding-venue-details/?seoURL=abc-hotel/&lang=en. Note that, despite your example stating otherwise, this will copy the trailing slash to the seoURL parameter value.


    Additional:

    Although /wedding-venue-details/?seoURL=abc-hotel/ isn't strictly a valid end-point. This is still reliant on other Apache modules/directives to route the request to a file (or "front-controller") eg. index.html (or index.php) to actually handle the request. For instance, this should probably be /wedding-venue-details/index.html?seoURL=abc-hotel/ (or /wedding-venue-details/index.php?seoURL=abc-hotel/ if using PHP).