[英]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.