htaccess重定向到维护文件

时间:2016-07-28 07:38:37

标签: php apache .htaccess redirect mod-rewrite

我在公共目录中有一个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 - 或任何域名?

3 个答案:

答案 0 :(得分:2)

你可以有这样的规则:

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

答案 1 :(得分:1)

尽管已经回答并接受了这一点,但值得一提的是,如果您的维护页面是临时的,那么您应该返回正确的http响应,否则搜索引擎可能会丢失或重新索引页面错误。< / p>

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

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作为维护页面,然后触摸 holding.enable以使服务器切换到它而无需重启(不要忘记 rm 它当我们完成时)。重写规则上的 503 返回代码和 ErrorDocument 503 确保搜索引擎认为这是暂时中断,并且不会开始取消列出我们的页面。< / p>

答案 2 :(得分:0)

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

askapache - cheatsheet

以及一些例子

askapache - examples

虽然值得尝试,因为它会使用root ^ $并将其重写到您要使用的子目录中:

RewriteBase /
ReqwriteRule ^$ /sub/web1/