Bra*_*hde 11 apache .htaccess mod-rewrite
我试图在我的.htaccess文件中定义一个环境变量,然后使用该变量运行重写条件.以下是我的.htaccess文件中的内容,但重写不起作用:
RewriteEngine on
#set to 'live' or 'maintenance'
SetEnv ENVIRONMENT maintenance
#If the ENVIRONMENT variable is 'mainetnance' then show a maintenance page to the users
RewriteCond %{ENV:ENVIRONMENT} maintenance
RewriteRule ^(.*)$ /maintenance.html
Run Code Online (Sandbox Code Playgroud)
这样做的目的是通过让PHP编辑.htaccess文件来编程,将网站设置为维护模式,当它从GitHub的一个钩子接收到一个post请求时,可以获取更新的repo.
Jef*_*rey 17
mod_rewrite不使用通过SetEnv设置的变量,而是使用此方法:
#set to 'live' or 'maintenance'
RewriteRule .* - [E=STATUS:maintenance]
#If the ENVIRONMENT variable is 'maintenance' then show a maintenance page
RewriteCond %{REQUEST_URI} !maintenance.html [NC]
RewriteCond %{ENV:STATUS} ^maintenance$
RewriteRule ^.*$ /maintenance.html [L]
Run Code Online (Sandbox Code Playgroud)
底部三行的第一行确保一旦用户被重定向到文件"maintenance.html",它就不会再被重定向.此外,用户不断被重定向到同一文件,导致500内部服务器错误,说"AH00124:由于可能的配置错误,请求超过了10个内部重定向的限制".
我发现几乎每个例子都不完整,所以我把我的解决方案带到了桌面上.我需要根据我的服务器环境(本地或生产)创建变量,然后根据该服务器环境运行重写.具体来说,如果环境是生产,我想强制https和www.
为什么不为每个服务器环境提供唯一的.htaccess文件?因为,我想在我的Git存储库中包含.htaccess,而不用担心搞砸了我的一个环境.
您需要知道的第一件事是所有这些必须在mod_rewrite中发生,这意味着您必须在Apache实例中启用mod_rewrite.如果您不知道如何检查,请创建一个phpinfo页面(http://www.phpinfofile.com/)并在"已加载的模块"部分中搜索"mod_rewrite".
.htaccess代码:
<IfModule mod_rewrite.c>
# Set SERVER_ENV=production if HTTP_HOST matches my production URL
RewriteCond %{HTTP_HOST} ^(www\.)?mysite\.com$ [NC]
RewriteRule .* - [E=SERVER_ENV:production]
# Force www. if SERVER_ENV is production
RewriteCond %{ENV:SERVER_ENV} ^production$
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Force https if SERVER_ENV is production
RewriteCond %{ENV:SERVER_ENV} ^production$
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Set SERVER_ENV=local if HTTP_HOST matches my local URL
RewriteCond %{HTTP_HOST} ^www-local\.mysite\.local$ [NC]
RewriteRule .* - [E=SERVER_ENV:local]
</IfModule>
Run Code Online (Sandbox Code Playgroud)
笔记:
RewriteCond行应该在RewriteRule之前,并且应该如图所示组合在一起.在重写规则启动之前,您必须满足一个或多个重写条件.
如果HTTP_HOST是"本地",我正在设置一个不同的变量.我没有任何使用"本地"变量的重写条件/规则 - 我只是为了指示而在这里设置它.
小智 5
有点晚-但是对于所有其他正在搜索的人...
使用SetEnvIf-请参阅: mod_rewrite规则和setenv
SetEnvIf Request_URI“。*” ENVIRONMENT =维护
...
| 归档时间: |
|
| 查看次数: |
24313 次 |
| 最近记录: |