Search code examples
.htaccesshttp-redirecthttp-status-code-301

set up 301 redirect from subdirectory to specific html file


I'm running apache on ubuntu 14.04 and trying to set up 301 redirects. Redirection is working, but not as expected. Here's what I have:

#REDIRECTS
Options +FollowSymLinks
RewriteEngine On


# REMOVES INDEX.PHP
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

# REDIRECT SPECIFIC PAGES
Redirect 301 /main http://mikeheavers.com
Redirect 301 /main/ http://mikeheavers.com
Redirect 301 /main/code http://mikeheavers.com/tutorials.html
Redirect 301 /main/code/ http://mikeheavers.com/tutorials.html

The first two redirect 301s work, but the rest, such as /main/code, try to redirect to http://mikeheavers.com/code and note http://mikeheavers.com/tutorials.html. What am I doing wrong?


update: note that I need to be able to redirect urls both containing and not containing the trailing slash


Solution

  • Don't mix mod_rewrite rules with mod_alias that has Redirect directive. Use this:

    #REDIRECTS
    Options +FollowSymLinks
    RewriteEngine On
    
    # REDIRECT SPECIFIC PAGES
    RewriteRule ^main/?$ http://mikeheavers.com [L,NC,R=301]
    RewriteRule ^main/code/?$ http://mikeheavers.com/tutorials.html [L,NC,R=301]
    
    # REMOVES INDEX.PHP
    RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php/$1 [L]
    

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