【问题标题】:Apache .htaccess redirect if folder not present如果文件夹不存在,Apache .htaccess 重定向
【发布时间】:2012-02-08 14:45:29
【问题描述】:
【问题讨论】:
标签:
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]