.htaccessmod-rewrite

htaccess RewriteRule: Remove and replace


I would like to redirect via .htaccess, old URL is like

https://www.domain.de/something/?action=login&params=1

New URL should be like:

https://www.domain.de/something/login.php?params=1

So, in short words:

Remove: ?action=

Use action text as script name: login should be the script name login.php

All following parameters should be appended in unchanged way.

Any ideas for that? I guess it must be split into two rules?

I tried like that, but "something" and the action param are still added after login.php? and I would have to implement for each script name manually:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} .*action=login.*
RewriteRule ^(.*) https://%{HTTP_HOST}/something/login.php?$1 [QSA,L]
</IfModule>

Solution

  • You may use this redirect rule in your site root .htaccess:

    RewriteEngine On
    
    RewriteCond %{QUERY_STRING} ^(.*&)?action=([^&]+)(?:&(.*))?$ [NC]
    RewriteRule ^ %{REQUEST_URI}%2.php?%1%3 [L,R=302,NE]
    

    Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.

    However if you don't want full redirect (URL to change in browser) then remove R flag from this rule.