Home > Net >  htaccess rule for redirecting when parameters are present
htaccess rule for redirecting when parameters are present

Time:08-10

RewriteEngine On
RewriteRule ^$ /index.phtml [R,L]
RewriteRule ^index.phtml. $ /index.php$1 [R,L]

I have 2 urls like https://www.example.com/index.phtml and https://www.example.com/index.php which both point to very different sites. I want to redirect to index.php in case there are any parameters found after index.phtml.

For example, https://www.example.com/index.phtml?a=b should go to https://www.example.com/index.php?a=b (second rule). I am trying the above rules but the second one isn't matching (the first rule works fine). Thanks for any help/suggestions

Please ask if you need any more details.

CodePudding user response:

You may use this code in site root .htaccess:

RewriteEngine On

# if there is a query string then redirect
# /index.phtml to /index.php 
RewriteCond %{QUERY_STRING} .
RewriteRule ^(?:index\.phtml)?$ /index.php [L,NC]

# redirect landing page to /index.phtml
RewriteRule ^$ /index.phtml [R=302,L]

Note that QUERY_STRING get automatically appended to target URL so /index.phtml?a=b will be redirected to /index.php?a=b.

Make sure to clear your browser cache before testing this change.

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

CodePudding user response:

With your shown samples, please try following .htaccess rules file. Please make sure that your htaccess file and index.php are present in same folder.

Also make sure to clear your browser cache before testing your URLs.

RewriteEngine ON
##For without query string rules.
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^index\.phtml/?$ index.php [R=301,NC,L]

##For query string rules.
RewriteCond %{THE_REQUEST} \s.index\.phtml\?([^=]*=\S )\s [NC]
RewriteRule ^ index\.php?%1 [R=301,L]
  • Related