在.htaccess中使用基于环境变量的RewriteCond

时间:2013-07-25 08:13:57

标签: 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

这样做的目的是通过让PHP编辑.htaccess文件,当它从GitHub的一个钩子中获取一个post请求来拉回repo进行更新时,以编程方式将站点设置为维护模式。

3 个答案:

答案 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:

  1. The first variable name is "SERVER_ENV" and the value is "production". This variable name/value could be anything. For example, you could use MY_ENVIRONMENT:live. After you've created this variable in .htaccess, you should be able to find it referenced in your phpinfo file - a great way to check that it's there.

enter image description here

  1. 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.

  2. 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

...