INSIDE
/pages/
我有PHP文件。例如,
projects.php
。我尝试在
.htaccess
规则中写入urlexample.com/projects
并从/pages/projects.php
打开文件,并与以下内容一起使用:RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(.+)
RewriteRule !\.[a-z0-4]{2,4}$ /pages/%1.php [NC,L]
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]
我的问题是,当我转到rootexample.com
时,而不是打开
index.php
它正在打开
/pages/
目录,但是如果我明确地转到example.com/index.php
,它可以正常工作。
我不希望在URL中显示
index.php
,因此我需要将根排除在我的规则之外,并在URL持续
index.php
时使其打开。
example.com
要排除被重写为# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]
/pages/
(0或更多)更改为index.php
(1或更多),以使其与root的请求不匹配(一个空的url path,in
*
)。
其他词:
+
cance,您已经在前面的规则/条件中做了类似的事情,即通过在condpattern
中使用
.htaccess
,即。
RewriteRule (.+) /pages/$1 [L]
.我考虑了另一种解决方案:
+
您想隐藏
RewriteCond %{REQUEST_URI} /(.+)
。这可以通过404错误来完成。
所以你可以做:
RewriteEngine On
RewriteBase /
# Hide the "pages" directory and all PHP files from direct access.
RewriteRule ^pages\b|\.php$ - [R=404]
# Rewrite clean-URL pages to the PHP files inside the "pages" directory:
# If the request isn't a file.
RewriteCond %{REQUEST_FILENAME} !-f
# If the request isn't a folder.
RewriteCond %{REQUEST_FILENAME} !-d
# If the PHP page file exists.
RewriteCond %{DOCUMENT_ROOT}/pages/$0.php -f
# /your-page?param=foo is rewritten to /pages/your-page.php?param=foo
# The L flag isn't suffisient because the rewrite rule to protect PHP files
# above will take over in the second loop over all the rewrite rules. To stop
# here we can use the newly END flag which stops completely the rewrite engine.
RewriteRule ^.*$ pages/$0.php [END,QSA]
但您可能还需要避免有人要求index.php
RewriteRule ^index\.php - [R=404]
。因此,我使用的是与目录和PHP文件扩展程序匹配的正则态度(仅此处的小写,但是您可以在
/pages
启用caseI
nsentsive标志的地方使用
/pages/your-page.php
)。
对于重写本身,我将用\.(?i)php
捕获the的URL,该URL将在(?i)
反向中可用,然后可以在重写规则本身和重写条件中使用。如果请求不是目录或现有文件,那么我们必须检查结果重写的URL是否实际上是
^.*$
目录中的现有PHP文件。
I使用
$0
标志,以便将查询参数保留在生成的URL中。然后,PHP脚本可以通过
pages
轻松访问它们。我希望您也可以通过检查其他环境变量来获得它们,如果您不使用此标志。我还必须使用类似于QSA
last标志的
$_GET
标志,但完全阻止了重写规则执行。如果您使用END
标志而不是标志,问题是因为L
将匹配重写规则以隐藏PHP文件,因此您将获得404错误,因为重写规则的整个过程是第二次运行的。重写引擎循环仅在输入URL不再通过重写规则更改时停止。是的,这花了我很长时间才能理解重写规则不仅像在配置文件中显示的那样运行一次!