.htaccess rewrite without www AND redirect to subdirectory
Solution 1
Try this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*)$ http://example.com/$1 [R=301,QSA,L]
RewriteCond %{REQUEST_URI} !^/(wiki|blog|style|forum)
RewriteRule ^(.*)$ http://www.example.com/forum/$1 [R=301,QSA,L]
Solution 2
I would use these rules:
# redirect www.example.com to example.com
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301]
# prefix everything but /forum/, /wiki/, /blog/, /style/ with /forum/ and rediret to it
RewriteRule !^(forum|wiki|blog|style)/ /forum%{REQUEST_URI} [L,R=301]
The second rule could additionally be replaced by this one to check the existence of the first path segment for every request.
# check if first segment of requested URI path is either missing
RewriteCond $0 ^$ [OR]
# or cannot be mapped to an existing directory
RewriteCond %{DOCUMENT_ROOT}$0/ !-d
RewriteRule ^[^/]* /forum%{REQUEST_URI} [L,R=301]
Toby Allen
Long Time Delphi Developer. Not Quite so Long PHP Developer. Laravel Developer. VBA Shark for a while. Once did some POP11, Lisp and Prolog. Once learned to enjoy Objective-C IPhone Development. Perforce Fan, now a bit of a Git. Any code I contribute to StackOverflow can be used by any person for any purpose. GitHub/tobya / @toflidium GitMySite/ DocTo
Updated on June 04, 2022Comments
-
Toby Allen almost 2 years
I'd like to redirect
www.example.com/*
toexample.com/*
And at the same time redirect
example.com/*
toexample.com/forum/*
But I also have
/wiki/
and/blog/
and/style/
, so I don't want to redirectexample.com/style/*
toexample.com/forum/style/*
This is what I have at the moment, which is not working quite correctly:
Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^example\.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !^/forum/ RewriteRule ^(.*)$ forum/$1 [R=301,L]
Clarification: my question can be asked in a simpler way.
I'd like to redirect an empty REQUEST_URI or /, or a non-existent file only if it is in the root directory to /forum/.
-
Admin about 15 yearsThis is what I have at the moment, which is not working quite correctly: Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !^example\.com$ [NC] RewriteRule ^(.*)$ example.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !^/forum/ RewriteRule ^(.*)$ forum/$1 [R=301,L]
-
Derek Greer over 12 yearsThis was never answered. Did you ever find a way to redirect to forum without ending up at www.example.com instead of just example.com?
-
Admin about 15 yearsisn't there a way without specifying all the subdirectories? I currently have only 4, but there will probably be more later... Thanks for your answer!