Reputation: 413
I have a site with only 2 sub pages that i want to keep, i want to redirect all other sub pages to homepage. This is my current htaccess code:
# this is to disable varnish caching on my server
Header set Set-Cookie "_asomcnc=1; max-age=900; path=/;"
RewriteEngine On
# redirect to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
# redirect index.html to root
RewriteBase /
RewriteRule ^index\.html$ / [NC,R,L]
# remove trailing slash
RewriteRule ^(.*)/$ /$1 [L,R=301]
I tried few examples i found here on stack overflow but i keep getting redirect loops, or my css file and images are not loaded. So lets say i want to load all files from these two folders:
And also i want to keep 2 subpages:
Everything else should be redirected to homepage.
Upvotes: 1
Views: 1951
Reputation: 74098
To exclude pages from being rewritten, you can either use RewriteCond
with %{REQUEST_URI}
or short circuit the rule chain.
To exit early, insert these rules at the beginning
RewriteRule ^css - [L]
RewriteRule ^images - [L]
RewriteRule ^subpage1.html$ - [L]
RewriteRule ^subpage2.html$ - [L]
And then redirect everything else to the homepage, unless it is already the home page, of course
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^ / [R,L]
To do the same with RewriteCond
RewriteCond %{REQUEST_URI} !^/css
RewriteCond %{REQUEST_URI} !^/images
RewriteCond %{REQUEST_URI} !^/subpage1.html$
RewriteCond %{REQUEST_URI} !^/subpage2.html$
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^ / [R,L]
This redirects to the home page, but only if REQUEST_URI
is not css and not images and not subpage1.html and not subpage2.html and not already the home page.
When everything works as it should, you may replace R
with R=301
. Never test with R=301
.
Upvotes: 3