使用mod_rewrite实现重定向并屏蔽指定目录访问的技术问题
问题描述
我的http.conf已将mydomain.com指向/var/html/www目录,该目录下存在production/version10.7文件夹,包含所有HTML文件(含index.html)。需求如下:
- 用户访问
mydomain.com时,地址栏显示mydomain.com/version10.7/index.html; - 内部实际从
/production/version10.7/目录读取文件提供服务。
当前/var/html/www下的.htaccess配置如下:
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=307] RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC] RewriteRule ^$ /version10\.7/index.html [L,R=302] RewriteCond %{REQUEST_URI} !^/production/ RewriteRule ^(.*)$ /production/$1 [L]
现有问题:
- 用户访问
mydomain.com/production/version10.7时,不会被重定向至mydomain.com/version10.7/index.html,地址栏仍显示含production的路径; - 若移除
RewriteCond %{REQUEST_URI} !^/production/条件,会触发内部服务器错误(疑似循环)。
需要解决:
- 实现请求重定向至指定版本目录,同时禁止通过
production路径访问内容; - 解释为何移除上述条件会导致内部服务器错误。
解决方案
修改后的.htaccess配置如下:
RewriteEngine On # 强制跳转至HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=307] # 禁止直接访问production路径,重定向到对应公开版本路径 RewriteCond %{THE_REQUEST} /production/(\w+)/?(.*) [NC] RewriteRule ^production/(.*)$ /$1 [L,R=302] # 根路径访问时,重定向到指定版本的index.html RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC] RewriteRule ^$ /version10.7/index.html [L,R=302] # 内部重写:将公开路径请求映射到production目录的实际文件 RewriteCond %{REQUEST_URI} !^/production/ RewriteRule ^(.*)$ /production/$1 [L]
规则说明
- 强制HTTPS:保留原有规则,确保所有请求都通过HTTPS访问;
- 禁止production路径访问:通过
%{THE_REQUEST}匹配用户实际发起的请求行(而非内部重写后的路径),捕获production/后的内容,重定向到去掉production/的公开路径,既隐藏了内部目录结构,又避免用户直接访问production路径; - 根路径重定向:保留原有规则,确保访问根域名时自动跳转到指定版本的首页;
- 内部重写:保留原有条件和规则,仅对非
production开头的请求进行内部映射,将公开路径(如/version10.7/index.html)指向/production/version10.7/index.html,用户地址栏不会显示内部路径。
额外问题解答
移除RewriteCond %{REQUEST_URI} !^/production/条件后,RewriteRule ^(.*)$ /production/$1 [L]会匹配所有请求,包括已经被重写为/production/xxx的内部请求。例如:
- 用户请求
/version10.7/index.html,被重写为/production/version10.7/index.html; - 这个重写后的请求再次被规则匹配,又重写为
/production/production/version10.7/index.html; - 如此反复循环,直到Apache达到预设的重写次数上限(默认通常为10次),就会返回500内部服务器错误。
原条件的作用正是排除已经以/production/开头的请求,避免这种无限循环。
内容的提问来源于stack exchange,提问作者DerpMeister
相关产品推荐
相关产品推荐

