首页 文章

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

提问于
浏览
1

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

我正在寻找一组RewriteConds和RewriteRules来完成以下任务:

  • 删除www,如果存在于URL中

  • 重定向到文件夹(如果URL中尚未存在)

  • 保留URL的其余部分

我在一个特定的子文件夹(我们称之为/ webapp)中安装了一个Web应用程序,该子文件夹在URL上配置为 require 无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

显然,如果请求"correct" 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

    尝试:

    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]
    
  • 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 .

相关问题