首页 > 解决方案 > 使用 .htaccess 重写根文件夹以外的 URL

问题描述

我正在尝试使用 .htaccess 将 URL 重写为漂亮的 URL。我尝试了很多方法,总是得到或错误 500 或什么都没有发生。我的文件夹树如下所示:

 root
    index.php
    .htaccess
    p
        .htaccess
        citati.php 
        ...

当有人去https://example.com/p/citati/Test-test将其重写为https://example.com/p/citati?autor=时,我要做的是从我的“p”目录中测试测试所以我可以在我的 citati.php 文件中有 $_GET["auto"] 。我在“p”目录中有很多 .php 文件,所以这也是我在重写时需要担心的。这是我的 .htaccess 从根

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
RewriteRule ^(.+)p/citati\/(.+)$ p/citati?autor=$1 [NC]

这就是我现在在“p”目录中的 .htaccess 文件:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L,QSA]
RewriteRule ^p/citati\/(.+)$ p/citati?autor=$1 [NC]
</IfModule>

我是否可以从根 .htaccess 文件或从“p”目录 .htaccess 实现这一点并不重要,我只是想以某种方式做到这一点。

标签: regex.htaccess

解决方案


根据您显示的示例,请确保您的根目录的 htaccess 规则文件如下。

RewriteEngine ON
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

对于您的p目录/文件夹,具有如下的 htaccess 规则文件。您需要使用与 root htaccess 相同的规则,您可以继承它。

RewriteOptions InheritBefore
RewriteEngine ON
RewriteBase /p/

RewriteCond %{THE_REQUEST} \s/(citati[^.]*)\.php\s [NC]
RewriteRule ^ %1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/(.*)/?$ $1.php?autor=$2 [NC,L]

推荐阅读