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

问题描述

我有 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

解决方法

您可以在站点根目录 .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]