regex - 使用 .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 实现这一点并不重要,我只是想以某种方式做到这一点。
解决方案
根据您显示的示例,请确保您的根目录的 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]
推荐阅读
- swift - 在 Firebase 上获取用户 Uid 字典
- r - 从 R 中的高斯过程生成函数数据
- .htaccess - htaccess 太多重定向
- sql - 选择上一个动作之后的第一个动作实例
- typescript - 如何将导出的 keyof 转换为字符串类型
- javascript - 打开 Chrome Devtools 重新加载 Hulu 会导致奇怪的行为
- postgresql - Peewee SQL - 如何在查询中使用 Python any() 和 all() 运算符
- python-3.x - 与直接在笔记本中的 colab 上运行相同的代码相比,在 colab 中运行 python 脚本非常慢
- aws-lambda - AWS HTTP API Gateway:阶段变量
- python - ModuleNotFoundError:没有名为“PIL”的模块