Search code examples
.htaccessmod-rewriteapache2apache2.2

Rewrite, Redirect, and avoid duplicate content


I'm trying to redirect a single page using .htaccess. The actual file is /abc.php, I want it to appear as /abc. So these are my pseudo-rules:

  • if the user hits /abc.php, rewrite the url as /abc
  • if the user hits /abc, serve /abc.php

For SEO purposes, only one of /abc and /abc.php should be available.

My naive approach is this:

Redirect 301 /abc.php /abc
RewriteRule ^abcs$ /abc.php [NC,L]

This is causing infinite, looping redirects. How do I do this correctly?


Solution

  • You can use this code in your DOCUMENT_ROOT/.htaccess file:

    RewriteEngine On
    RewriteBase /
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+(abc)\.php[\s?] [NC]
    RewriteRule ^ %1? [R=302,L]
    
    # internal forward from pretty URL to actual one
    RewriteRule ^(abc)/?$ $1.php [L,NC]