我正在尝试在.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
这样做的目的是通过让PHP编辑.htaccess文件,当它从GitHub的一个钩子中获取一个post请求来拉回repo进行更新时,以编程方式将站点设置为维护模式。
答案 0 :(得分:15)
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]
底部三行的第一行确保一旦用户被重定向到“maintenance.html”文件,它就不会再被重定向。此外,用户不断被重定向到同一文件,导致500内部服务器错误,说“AH00124:由于可能的配置错误,请求超过了10个内部重定向的限制。”
答案 1 :(得分:7)
I found that nearly every example fell short of complete, so I'm bringing my solution to the table. I needed to create a variable based on my server environment - either local or production - then run rewrites based on that server environment. Specifically, if the environment is production, I want to force https and www.
Why not have a unique .htaccess file for each server environment? Because, I want to include .htaccess in my Git repository and not worry about screwing up one of my environments.
The first thing you need to know is that all of this must occur within mod_rewrite, which means that you must have mod_rewrite enabled in your Apache instance. If you do not know how to check this, create a phpinfo page (http://www.phpinfofile.com/) and do a search for "mod_rewrite" in the "Loaded Modules" section.
The .htaccess code:
<link rel="icon" href="/icon.ico">
Notes:
The RewriteCond lines should be before the RewriteRule and should be grouped together as shown. You can have 1 or more rewrite conditions that must be met before the rewrite rule kicks in.
I'm setting a different variable if HTTP_HOST is "local". I don't have any rewrite conditions/rules that use the "local" variable - I'm just setting it here for the sake of instruction.
答案 2 :(得分:4)
迟到了 - 但是对于其他所有人来说......
使用 SetEnvIf - 请参阅: mod_rewrite rule and setenv
SetEnvIf Request_URI“。*”ENVIRONMENT = maintenance
...