mod_rewrite:删除www并重定向到文件夹(如果尚未在URL中)

时间:2012-10-18 22:09:20

标签: apache .htaccess mod-rewrite redirect

第一次来到这里,我有点像mod_rewrite和regex noob,所以如果我错过了什么,请告诉我。我整天都在这里和其他地方搜索过,但找不到我需要的东西。

我正在寻找一套可以完成以下任务的RewriteConds和RewriteRules:

  • 删除www,如果存在于网址
  • 重定向到文件夹(如果网址中尚未显示)
  • 保留网址的其余部分

我在特定的子文件夹(我们称之为/ webapp)中安装了一个Web应用程序,该子文件夹配置为要求在网址上没有www。如果用户包含www,它会向用户显示一条愚蠢的恼人信息。我可以深入了解应用程序并重新编程,但我想通过.htaccess和mod_rewrite为用户处理它,同时将它们转储到文件夹中,如果他们忘记输入它,使用301重定向完成所有这些操作

例如,我想要以下任何一个请求

http://www.mydomain.org/webapp/anything
http://www.mydomain.org/anything
http://mydomain.org/anything

重定向到

http://mydomain.org/webapp/anything

显然,如果请求“正确”的URL(以http://mydomain.org/webapp/开头),则根本不会重写。

到目前为止,我最好的猜测如下:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.mydomain\.org$ [NC]
RewriteRule ^(.*)$ http://mydomain.org/$1 [R=302]

RewriteCond %{REQUEST_URI} !^/webapp.*$ [NC]
RewriteRule ^(.*)$ http://mydomain.org/webapp/$1 [R=302]

根据http://htaccess.madewithlove.be/这似乎有效,但实际上并非如此。

提前致谢。

2 个答案:

答案 0 :(得分:0)

尝试:

RewriteCond %{HTTP_HOST} ^www\.mydomain\.org$
RewriteRule ^ mydomain.org/$1 [L,R=301]

RewriteCond %{REQUEST_URI} !^/webapp.*$
RewriteRule ^/(.*) mydomain.org/webapp/$1 [L,R=301]

答案 1 :(得分:0)

我自己在这里找到答案:BowlerHat

看起来像这样:

# First just remove the www
RewriteCond %{HTTP_HOST} ^www\.mydomain\.org$ [NC]
RewriteRule ^(.*)$ http://mydomain.org/$1 [L,R=301]

# Now redirect into the folder
RewriteCond %{REQUEST_URI} !webapp/ [NC]         # if the provided URI does not start with /webapp,
RewriteRule (.*) http://mydomain.org/webapp/ [L,R=301]         # redirect user to /webapp/ root

我决定如果用户试图访问mydomain.org/somethingsomething,只是将它们发送到webapp的根目录,而不是/ webapp / somethingsomething。