htaccess重定向到维护文件


htaccess redirect to a maintainance file

我在公共目录中有一个htaccess:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    RewriteEngine On
    RewriteBase /sub/web1/
    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    # HERE I NEED SOM MAGICAL ONELINER TO REDIRECT STUFF TO MAINTENANCE.HTML
    # BUT NO IDEA HOW TO WRITE IT ;(
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

我想在里面添加一些规则,所以当我取消注释规则时,所有命中http://example.com/sub/web1/或该行中任何文件的链接都将重定向到http://example.com/sub/web1/maintenance.html

我已尝试添加:DirectoryIndex maintenance.html但这只是重定向http://example.com/sub/web1/,如果我有一些子文件夹或特定的文件,比如http://example.com/sub/web1/posts,那就没用了。

有没有哪种oneliner可以提取域名,这样就不必绝对键入?那么,不需要example.com或任何域来键入规则?

您可以有这样的规则:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>
    RewriteEngine On
    RewriteBase /sub/web1/
    # uncomment line below to route everything to maintenance.html
    # RewriteRule !^maintenance'.html$ maintenance.html [L,NC]
    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]
    # HERE I NEED SOM MAGICAL ONELINER TO REDIRECT STUFF TO MAINTENANCE.HTML
    # BUT NO IDEA HOW TO WRITE IT ;(
    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

尽管这已经得到了回答和接受,但值得一提的是,如果您的维护页面是临时的,您确实应该返回正确的http响应,否则搜索引擎可能会错误地删除或重新索引页面。

在我的公司,我们使用这样的东西:

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/holding/holding.html -f
RewriteCond %{DOCUMENT_ROOT}/holding/holding.enable -f
RewriteCond %{SCRIPT_FILENAME} !holding.html
RewriteRule ^.*$ /holding/holding.html [R=503,L]
ErrorDocument 503 /holding/holding.html

我们创建holding.html作为维护页面,然后touchholding.enable使服务器切换到它而不需要重新启动(完成后不要忘记rm它)。重写规则上的503返回代码和ErrorDocument 503

您可以使用%{HTTP_HOST}变量来获取在访问给定的htaccess文件时使用的当前域-这里有一个方便的备忘单:

askapache-备忘单

并举例说明

askapache-示例

尽管值得一试,因为它将使用root^$并将其重写到您想要使用的子目录:

RewriteBase /
ReqwriteRule ^$ /sub/web1/