rewrite and replace value of a get param inside url

original address -
or without index.php - i.e. just -

what I want in address bar -

here is my try - without success:

RewriteEngine ON
RewriteCond %{THE_REQUEST} \?c=bs [NC]
RewriteRule ^ %1? [R=301,L,NE]
RewriteRule ^([^/.]+)/?$ ?c=blue-sky [L,QSA]  

pls help

1 answer

  • answered 2022-01-17 22:27 MrWhite

    what I want in address bar -

    Assuming you have already changed your internal links to this desired canonical URL then you can implement the following in .htaccess to externally redirect /index.php?c=bs (or /?c=bs) to /blue-sky for the benefit of SEO. Followed by a rewrite to internally rewrite requests for /blue-sky back to /index.php?c=bs.

    For example (assuming you are on Apache 2.4):

    RewriteEngine On
    # Redirect "/index.php?c=bs" (or "/?c=bs") to "/blue-sky"
    RewriteCond %{QUERY_STRING} ^c=bs$
    RewriteRule ^(index\.php)?$ /blue-sky [QSD,R=301,L]
    # Rewrite (internally) "/blue-sky" back to "/index.php?c=bs"
    RewriteRule ^blue-sky$ index.php?c=bs [QSA,END]

    The QSD flag on the first rule is required to discard the original query string (ie. c=bs) from the redirect response. Otherwise, it will redirect to /blue-sky?c=bs. This requires Apache 2.4

    The QSA flag on the second rule allows any additional query string parameters that might be present on the initial request being appended. eg. /blue-sky?foo=1 would be rewritten to index.php?c=bs&foo=1. If that is not required and you are not expecting any additional query string then remove the QSA flag.

    The END flag (as opposed to L) prevents any further loops by the rewrite engine and thus prevents the rewritten URL being redirected back to the canonical URL (which would otherwise result in an endless redirect loop). The END flag requires Apache 2.4.

    A look at your directives:

    RewriteCond %{THE_REQUEST} \?c=bs [NC]
    RewriteRule ^ %1? [R=301,L,NE]
    RewriteRule ^([^/.]+)/?$ ?c=blue-sky [L,QSA]

    The first rule would essentially redirect /<anything>?c=bs back to the document root, except that the %1 backreference is empty and without a RewriteBase directive, this will result in a malformed redirect, exposing the absolute filesystem directory.

    The second rule rewrites /<anything> to ?c=blue-sky, which should presuambly be c=bs (but that would result in a redirect loop since the rewrite engine starts over with the use of L, rather than END).

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum