【问题标题】:Apache .htaccess redirect if folder not present如果文件夹不存在,Apache .htaccess 重定向
【发布时间】:2012-02-08 14:45:29
【问题描述】:

我有一个网站,我需要在其中执行以下操作

如果http://example.com/user1不存在,将用户重定向到http://user1.example.com

同样http://www.example.com/user2 应该重定向到http://user2.example.com

这可以使用 .htaccess 文件吗?

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) http://%{HTTP_HOST} [R]

上面重定向到首页,但是我如何读取/之后的URL并按照上面的方式进行重定向?

【问题讨论】:

    标签: apache .htaccess redirect http-status-code-404


    【解决方案1】:
    RewriteCond %{SERVER_NAME} =example.com      # prevent infinite redirection
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^/([^/]+)$
    RewriteRule .* http://%1.%{SERVER_NAME} [R]
    

    REQUEST_URI 上有些繁琐的正则表达式确保只有 http://example.com/user1 方案的 URL 将被重定向(与 /user1/foo/bar 相反)。

    注意使用SERVER_NAME 而不是HTTP_HOST(后者is evil and should be avoided)。

    【讨论】:

      【解决方案2】:

      尝试将以下内容添加到 example.com 站点根目录中的 .htaccess 文件中。

      RewriteEngine on 
      RewriteBase / 
      
      #if on example.com host
      RewriteCond %{HTTP_HOST} ^example\.com$ [NC] 
      #and the directory/folder does not exist
      RewriteCond %{REQUEST_FILENAME} !-d
      #redirect to folder.example.com
      RewriteRule ^(\w+)$ http://$1.%{HTTP_HOST} [R,L]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-23
        • 1970-01-01
        • 2010-10-14
        • 2015-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-09-12
        • 1970-01-01
        相关资源
        最近更新 更多