Search code examples
apache.htaccessmod-rewrite

rewrite then redirecting to same page with .htaccess


Default URL: domain.com/contact.php

Rewrite URL to: domain.com/contactus

Then when I have to enter the default URL to: domain.com/contact.php it should redirect (open) to domain.com/contactus

I have tried

RewriteRule ^contactus$ contact.php [L]
RewriteRule contact.php contactus [NC,R=301,L]

Solution

  • You need one redirect rule to force new URI in browsers and one rewrite to forward new URI to php file:

    RewriteEngine On
    
    # redirect rule
    RewriteCond %{THE_REQUEST} \s/contact\.php[?\s] [NC]
    RewriteRule ^ /contactus? [L,R=301] 
    
    # rewrite rule
    RewriteRule ^contactus/?$ contact.php [L,NC]
    

    ? in target URI will remove existing query string.