.htaccess重写去除www并重定向到子目录

4
我想要进行重定向:
  • www.example.com/* 重定向到 example.com/*

同时,我还需要进行以下重定向:

  • example.com/* 重定向到 example.com/forum/*

但是我也有 /wiki//blog//style/,所以我不想要将以下内容进行重定向:

  • example.com/style/* 重定向到 example.com/forum/style/*

这是我目前的代码,但它并不能正常工作:

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]

澄清:我的问题可以更简单地表达。

我想要将一个空的REQUEST_URI或者/,或者一个不存在的文件(仅当它位于根目录下)重定向到/forum/


这是我目前拥有的代码,但它并不能正常运行:Options +FollowSymLinks RewriteEngine OnRewriteBase /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] - johnb2
这个问题从未得到解答。你是否找到了一种方法,可以在重定向到论坛时不会最终停留在www.example.com,而只是example.com? - Derek Greer
4个回答

2

试试这个:

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]

有没有一种方法可以不指定所有子目录呢?我目前只有4个,但以后可能会有更多... 感谢您的回答! - johnb2

1
我会使用以下规则:
# 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]

第二条规则可以额外被替换为这个规则,以检查每个请求的第一个路径段的存在。
# 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]

0

我觉得这应该可以运行。

RewriteEngine on
RewriteRule ^forum/(.*)$ forum/$1 [L]
RewriteRule ^wiki/(.*)$ wiki/$1 [L]
RewriteRule ^blog/(.*)$ blog/$1 [L]
RewriteRule ^style/(.*)$ style/$1 [L]

RewriteRule ^(.*)$ forum/$1 [L]

RewriteCond  %{HTTP_HOST}  ^www.example\.com$
RewriteRule ^(.*)$ http://example.com/$1

0

虽然我不是万事通,但对于你的www/非www问题,你可以尝试以下方法:

# Enforce www
# If you have subdomains, you can add them to 
# the list using the "|" (OR) regex operator
RewriteCond %{HTTP_HOST} !^(www|subdomain) [NC]
RewriteRule ^(.*)$ /exemple/$1 [L,R=301]

# Enforce NO www
RewriteCond %{HTTP_HOST} ^www [NC]
RewriteRule ^(.*)$ http://exemple.com/$1 [L,R=301]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接