Using mod_rewrite in .htaccess both in site root and in subdirectory
My dilemma:
In .htaccess on my root website:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
In .htaccess in subdirectory / foo
RewriteEngine On
RewriteRule ^page1\.html$ /foo/page2.html [R=301]
First, I'm trying to ensure that all requests include the beginning of www. In the second case, I redirect requests for page1.html to the foo subdirectory of page2.html, also in that subdirectory.
In my browser, trying to visit:
http://www.example.com/foo/page2.html <== works, good
http://www.example.com/foo/page1.html & lt == == redirects to http://www.example.com/foo/page2.html , good
http://example.com/foo/page1.html <== redirects to http://www.example.com/foo/page2.html , good
http://example.com/foo/page2.html <== no redirection happens, bad
==> Should redirect to: http: //**www.**example.com/foo/page2.html
As a result of experimentation, it would seem that the redirect rules in the .htaccess file in the site root of the site only take effect for requests to pages in that IF subdirectory , that this subdirectory does not contain an .htaccess file or it does and specifies a rewrite rule that takes effect for this specific request.
Can anyone see what I am doing wrong? ... How can I get the rewrite rule that www. if it's missing for http://example.com/foo/page2.html ?
Thanks hop it worked!
For the record, I had to change the rewrite rule in the file at the root of the site so that:
RewriteRule ^.*$ http://www.example.com%{REQUEST_URI} [R=301,L]
This is normal. Thank!
source to share
I'm not sure about the specifics of why the rules in /.htaccess
do not apply to /foo/.htaccess
. generally, files .htaccess
inherit rules in a directory structure, which can lead to all sorts of odd things happening. for your specific solution, you can simply place all relevant rules in your parent file .htaccess
as such:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^foo/page1\.html$ /foo/page2.html [R=301]
source to share