I have a folder in my root directory called pages
that I would like to hide from the URL when accessed. Currently, my URL looks like this: www.foo.com/pages/page.html
I would like to remove the folder name pages
in the URL but still direct users to the folder. How can I do this using the .htaccess
file? For clarity, I would like the final URL to look like this:
www.foo.com/page.html
I've taken a look at some StackOverflow answers and I am struggling to understand how I would edit my .htaccess file to make this adjustment. So far, this is what my .htaccess
file looks like:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^pages/
RewriteRule ^(.*)$ /$1 [L]
How do I change www.foo.com/pages/page.html
to www.foo.com/page.html
using .htaccess?
You actually need 2 rules to manage this:
301/302
redirect if a URL already has /pages/
(usually a cached URL in browsers / search results)/pages/
at the start of URIs to serve the right page from your hostYou can have these rule in your site root .htaccess:
RewriteEngine On
# To externally redirect /pages/pages.html to /page.html
RewriteCond %{THE_REQUEST} /pages/([^\s?]*)[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]
## To internally rewrite /pages.html to /pages/page.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/pages/ [NC]
RewriteRule .* pages/$0 [L]
Once you have verified that rules are working fine, you can then change 302
to 301
to make it a permanent redirect.