.htaccess重定向和RewriteRule(有或没有RewriteCond)的问题

时间:2016-02-26 15:13:55

标签: php apache .htaccess mod-rewrite

我必须设置网址 http://subdomain.example.com/test 并使其能够调用真实文件 /my-test-script.php

我无法理解以下代码的工作原理:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^\/?test\/?$
RewriteRule ^\/?(.*)$ /my-test-script.php [NC,L,QSA]

虽然这个不起作用:

RewriteEngine On
RewriteBase /

RewriteRule ^\/?test\/?$ /my-test-script.php [NC,L,QSA]

RewriteCond强制要求吗?如果没有,我会错过什么?

谢谢!

修改 .htaccess my-test-script.php 都在根目录中./。

编辑2: 有趣的更新:我认为它适用于

RewriteRule test /my-test-script.php [NC,L,QSA]

但不是

RewriteRule ^test$ /my-test-script.php [NC,L,QSA]

编辑3: 我创建了一个显示$ _GET参数的脚本:

RewriteCond %{REQUEST_URI} !^\/?show\-parameters\.php$
RewriteRule ^(.*)$ /show\-parameters.php?path=$1 [NC,L,QSA]

当我致电http://subdomain.example.com/test时,我看到了:

Array ( [path] => /var/www/html/client/project_name/domain/subdomain/test )

编辑4: 这是我的VirtualHost:

<VirtualHost *>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    RewriteEngine On

    ### HTTP: from www to non-www ###
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

    <Directory /var/www/html>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        allow from all

        RewriteBase /

    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName subdomain.example.com
    ServerAlias www.subdomain.example.com
    DocumentRoot /var/www/html/client/project_name/domain/subdomain

    RewriteEngine On

    ### HTTP: from www to non-www ###
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

    <Directory /var/www/html/client/project_name/domain/subdomain>
            Options -Indexes +FollowSymLinks +Multiviews
            AllowOverride All
            Order allow,deny
            allow from all

            RewriteBase /
    </Directory>

</VirtualHost>

[求助]编辑5: 我只是从.htaccess中删除了RewriteBase /行,现在可以使用以下规则:

RewriteEngine On
RewriteRule ^\/?test\/?$ /my-test-script.php [NC,L,QSA]

2 个答案:

答案 0 :(得分:1)

您的my-test-script.php位于.htaccess的同一级别吗?如果是这样,请执行以下操作:

RewriteEngine On
RewriteBase /

RewriteRule ^test/?$ my-test-script.php [NC,L,QSA]

答案 1 :(得分:0)

RewriteEngine On
RewriteBase /

RewriteRule ^/test/?$ /my-test-script.php [NC,L,QSA]

试试吧。在我的测试环境中,这对我有用。