首页 > 解决方案 > PHP 重写 URL htaccess 多个条件

问题描述

我正在尝试重写 URL 地址,但我没有取得太大进展。我读了很多书并尝试了,但我没有设法做我想做的事。如果有人给出一个想法,我会很高兴。我想做的是:

  1. 删除“ .php ”扩展名,例如。“ site.com/about
  2. 如果我输入“ site.com/index.php ”或“ site.com/index ”重定向到“ site.com
  3. 如果我键入“ site.com/profile.php?profile=alex ”以将 URL 重写为“ site.com/profile/alex

还要保留我包含的文件的路径,例如 css、js、图像或 php。

我分别尝试过的:

1. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L]

2. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L]

3. RewriteEngine On RewriteRule ^profile/(.+)[/]?$ profile.php?profile=$1

标签: php.htaccessurlurl-rewriting

解决方案


您可以在站点根目录 .htaccess 中有这些规则:

Options -MultiViews
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+profile\.php\?profile=([^\s&]+)\s [NC]
RewriteRule ^ /%1? [R=302,L,NE]

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))\.php[\s?] [NC]
RewriteRule ^ /%1%2 [R=301,L,NE]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ profile.php?profile=$1 [L,QSA]

推荐阅读