如何为多个子目录制定htaccess重写规则

Posted

技术标签:

【中文标题】如何为多个子目录制定htaccess重写规则【英文标题】:how to make htaccess rewrite rule for multiple sub directories 【发布时间】:2021-08-09 13:28:54 【问题描述】:

我有 3 个子目录,其中 index.php 文件具有相同的 url 参数:

example https://example.com/one/index.php?c=onestar https://example.com/two/index.php?c=onestar https://example.com/three/index.php?c=onestar

我正在使用以下代码从 URL 中删除 .php

RewriteEngine On

options +MultiViews
RewriteEngine On
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_FILENAME.php -f
RewriteRule !.*\.php$ %REQUEST_FILENAME.php [QSA,L]

如何使其对 SEO 友好 https://example.com/one/index/onestar。以及如何使其动态以在将来添加多个目录,例如https://example.com/four/index/onestar

【问题讨论】:

@anubhava 你知道解决方案吗? 对不起,我不知道htaccess,我正在尝试一些重写规则代码 重写规则 ^index/([a-zA-Z]+)$ index.php?c=$1 您可以做的任何事情 RewriteEngine On RewriteCond %HTTPS off RewriteRule ^(.*)$ https://%HTTP_HOST%REQUEST_URI [L,R=301]] 选项 +MultiViews RewriteEngine On RewriteCond % REQUEST_FILENAME !-d RewriteCond %REQUEST_FILENAME.php -f RewriteRule !.*\.php$ %REQUEST_FILENAME.php [QSA,L] 【参考方案1】:

您可以在站点根目录 .htaccess 中使用此代码:

Options -MultiViews
RewriteEngine On

# http => https
RewriteCond %HTTPS !on
RewriteRule ^ https://%HTTP_HOST%REQUEST_URI [L,R=301,NE]

# /one/index/onestar => /one/index.php?c=onestar
RewriteRule ^([\w-]+)/index/([\w-]+)/?$ $1/index.php?c=$2 [L,NC,QSA]

# hide .php
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_FILENAME.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

【讨论】:

感谢它的工作。但是如果我让它动态而不是使用 (one|two|three) 是否正确,我使用 (.*) 是的,我可以动态化,规则会进一步更新。

以上是关于如何为多个子目录制定htaccess重写规则的主要内容,如果未能解决你的问题,请参考以下文章

htaccess 列出目录并为其重写规则

从 HTACCESS 文件中的所有 ISAPI 重写 3 规则中排除目录

子域“m”。与 WordPress 和。 htaccess(在 htaccess 中的重写规则冲突。)

.htaccess 从子目录重写到根目录

.htaccess 如何为 public_html cpanel 工作

.htaccess重写合并