使用.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["autor"] 。我在“p”目录中有很多 .php 文件,所以这也是我在重写时需要担心的。这是我从 root 访问的 .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 实现这一点并不重要,我只是想以某种方式做到这一点。

回答

根据您显示的示例,请确保您的根目录的 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[^.]*).phps [NC]
RewriteRule ^ %1? [R=301,L]

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

  • It is working right now, thank you very much 🙂

以上是使用.htaccess重写根文件夹以外的URL的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>