对于不同的目录有两个重写规则,只有一个工作

时间:2016-10-14 14:29:42

标签: apache .htaccess redirect mod-rewrite

背景

我正在尝试为我的Apache服务器添加另一个重写规则,但我遇到了一个奇怪的问题。

我正在创建这个新规则导致原始规则中断(因为,不工作......我没有得到任何错误)。只会运行一个或另一个规则。

通过显示代码更容易解​​释......

代码

规则#1:

# Redirect hits from non-existent page to link shortener
<Directory /var/www/html/lnf>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . - [L]

RewriteRule ^/?([^/]+)/?$ link/link.php?a=$1 [L]
</Directory>

规则#2:

# Deny disallowed user agents (when adding this, it causes the first one to break)
<Directory ~ "/var/www/html/*">
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "(netscape|\.ru)" [nocase]
RewriteRule ^.*$ – [forbidden,last]
</Directory>

问题

为什么会发生这种情况,我该如何解决?

PS:请原谅我缺乏知识,在Apache方面,我仍然觉得自己是初学者。

更新

我有4个vhost用于HTTP,4个用于HTTPS。

/etc/apache2/sites-enabled/000-default.conf/default-ssl.conf中的四个是:

1。拒绝所有通常是机器人的公共IP的命中(这是在vhosts文件的顶部,如果没有其他的话,它就会被捕获):

<VirtualHost *:80 (and 443 in ssl)>
    ServerName catchall
    <Location />
        Require all denied
    </Location>
</VirtualHost>

2。 3个不同域的3个不同的虚拟主机

<VirtualHost _default_:80 (and 443 in ssl)>
ServerName (my domain)

### REDIRECT HTTP TO HTTPS (this is only in the 000-default.conf)
RewriteEngine On
RewriteCond %{HTTPS} off
#only change when using [mydomain.com] domain (the only public domain)
RewriteCond %{HTTP_HOST} ^mydomain\.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# doc roots, error logs, ssl certificates (I omitted this to save space)
</VirtualHost>

1 个答案:

答案 0 :(得分:0)

这样做:

# default rule applied to all locations
<Location />
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} "(netscape|\.ru)" [NC]
    RewriteRule ^ – [F,L]
</Location>

# catch all virtual host
<VirtualHost _default_:*>
    DocumentRoot "/var/www/html"
    ServerName catchall
    <Location />
        Require all denied
    </Location>
</VirtualHost>

# rules specific to mydomain.com placed here
<VirtualHost _default_:80>
    DocumentRoot "/var/www/html/lnf"
    ServerName mydomain.com
    DirectoryIndex index.php

    ### REDIRECT HTTP TO HTTPS (this is only in the 000-default.conf)
    Options +FollowSymLinks
    RewriteEngine On

    RewriteCond %{HTTPS} off
    #only change when using [mydomain.com] domain (the only public domain)
    RewriteCond %{HTTP_HOST} ^mydomain\.com$
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    RewriteRule ^/?([^/]+)/?$ /link/link.php?a=$1 [L,QSA]
</VirtualHost>