Search code examples
apache.htaccesshttp-redirectmod-rewriteurl-rewriting

I need help placing a 301 redirect in my htaccess file of my new php site


I have a php website and my current .htaccess file is as follows:

<IfModule mod_rewrite.c>

#Options +FollowSymlinks


RewriteEngine On


RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /index.php?page=$1 [NC,L,QSA]


Options -Indexes


</IfModule>

Now I want to do a 301 redirect on a URL. From example.com/folder/old-url-london.htm to example.com/new-url-london/

The problem is everytime I try something I get:

www.example.com/new-url-london/?page=folder/old-url-london.htm

Now I can't change this line (RewriteRule ^(.*)$ /index.php?page=$1 [NC,L,QSA]) as it is essential to the working of the website.

Any ideas?

I tried the following:

Redirect 301 /folder/old-url-london.htm example.com/new-url-london/

as well as

RewriteRule ^folder/old-url-london.htm$ /new-url-london/ [R=301,L]

Solution

  • Sounds like you are perhaps putting the rule in the wrong place. Or used the Redirect directive. And/or are perhaps now seeing a cached response.

    You need to use mod_rewrite RewriteRule to avoid conflicts with the existing rewrite AND the rule needs to be at the top of the file, before the existing rewrite and ideally after the RewriteEngine directive.

    For example:

    Options +FollowSymlinks -Indexes
    
    RewriteEngine On
    
    RewriteRule ^folder/old-url-london\.htm$ /new-url-london/ [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) index.php?page=$1 [QSA,L]
    

    You will need to clear your browser cache before testing, since any erroneous 301 (permanent) redirects will have been cached by the browser. Test first with 302 (temporary) redirects for this reason.

    Don't forget to backslash-escape literal dots in the regex.

    I tidied up a few other bits:

    • <IfModule> wrapper is not required.
    • Combined Options at the top and re-enabled FollowSymLinks (since it is required by mod_rewrite)
    • RewriteBase is not required in the directives you've posted.
    • Removed spurious spacing.
    • NC flag not required on the rewrite since the pattern .* already matches everything.
    • The anchors on the pattern ^(.*)$ are not required since regex is greedy by default.