Mod将带有查询字符串的重定向URL重写为漂亮的URL

Lan*_*nce 2 .htaccess mod-rewrite

在 mod rewrite 的帮助下,我成功地将我的 URL 从查询字符串中带有多个参数的丑陋 URL 更改为干净的 URL。但是,我的网站有很多网址。我没有返回并编辑每个锚标记上的 href 属性,而是尝试在 .htaccess 文件中编写一个重定向函数,该函数会自动将旧 URL 重定向到新 URL。

在我的 .htaccess 文件中,我有以下内容:

RewriteEngine On

Redirect teams.php?league=$1&team=$2&year=$3&tab=$4 teams/(.*)/(.*)/(.*)/(.*)

RewriteCond %{REQUEST_URI} !^(css|js|img)/
RewriteRule ^teams/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ teams.php?league=$1&team=$2&year=$3&tab=$4 [L]
Run Code Online (Sandbox Code Playgroud)

没有运气……有什么想法吗?

谢谢

Jon*_*Lin 5

You need to do a check that the old URL with the php in it is actually being requested by matching against %{THE_REQUEST}, otherwise it'll redirect loop forever (e.g. user goes to team.php, serve redirects to teams, browser requests teams, server rewrites as teams.php, server sees "teams.php" and redirects to teams, browser requests teams, server rewrites as teams.php, etc. etc.)

RewriteEngine On

# redirect when the user actually requests for teams.php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /teams\.php\?league=([^&]+)&team=([^&]+)&year=([^&]+)&tab=([^\ ]+)
RewriteRule ^teams\.php$ /teams/%1/%2/%3/%4? [R=301,L]

# internally rewrite any /teams/ URI
RewriteCond %{REQUEST_URI} !^(css|js|img)/
RewriteRule ^teams/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ teams.php?league=$1&team=$2&year=$3&tab=$4 [L]
Run Code Online (Sandbox Code Playgroud)