繁体   English   中英

Apache 2.4 .htaccess-将所有请求指向index.html,但有一个异常

[英]Apache 2.4 .htaccess - Point All Requests to index.html With One Exception

我目前有以下.htaccess

<IfModule mod_rewrite.c>
    Options Indexes FollowSymLinks
    RewriteEngine On
    RewriteBase /production/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

Web服务器的文档根目录当前是上面引用的/production文件夹( .htaccess文件位于父文件夹中,因为/production被删除并在每次提交代码时都进行重建)。 上面的代码会将所有访问我网站的信息定向到index.html

我想对此例外。 如果请求是www.mydomain.com/specialrequest ,我希望运行父文件夹中的一个名为script.php的PHP脚本。

要查看,这是我的/var/www/html目录:

-html
    -production
    -anotherfolder
    -.htaccess
    -script.php

Apache指向/var/www/html/production ,我希望所有请求都转到该目录中的index.html文件,除非该请求为/specialrequest在这种情况下,我希望script.php运行。

Apache指向/var/www/html/production

因此, /var/www/html/production确实定义为DocumentRoot 因此,您的.htaccess文件位于文档根目录上方 您要重写的文件(收到此特殊请求后)也位于文档根目录的上方。

不幸的是,您无法使用.htaccess重写到文档根目录之上的文件(无论该.htaccess文件位于何处)。 这是因为按目录.htaccess文件中的RewriteRule 替换采用URL路径 ,因此尝试重写到文档根目录之上的URL完全无效。 但是,如果可以访问服务器配置(或虚拟主机),则可以使用此方法重写到文件系统路径 (包括文档根目录上方)-而不是URL路径。

因此, script.php将需要在文档根目录下,才能使用.htaccess进行此操作。 在这种情况下,您可以执行以下操作:

RewriteEngine On

# Exception
RewriteRule ^specialrequest$ /script.php [L]

# Front controller
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

但是在这种情况下, script.php需要位于/html/production/script.php (在文档根目录下),而不是/html/script.php (在文档根目录上)-就像您当前的文件系统一样结构体。

顺便说一句, .htaccess文件中的RewriteBase /production/指令完全多余。 无论如何,您都没有使用相对路径替换,但是由于/production文档根目录,因此/index.html (文档根目录相对URL路径)将始终重写为/production/index.html


但是,如果可以直接在服务器配置(或虚拟主机)中编写此代码,则可以执行所需的操作。 例如:

RewriteEngine On

# Rewrite to filesystem path (in the server config)
RewriteRule ^/specialrequest$ /var/www/html/script.php [L]

# Front controller
RewriteRule ^/index\.html$ - [L]
RewriteCond %{LA-U:REQUEST_FILENAME} !-f
RewriteCond %{LA-U:REQUEST_FILENAME} !-d
RewriteRule ^/. /index.html [L]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM