重写URL的参数并删除查询字符串

时间:2017-05-12 19:54:17

标签: .htaccess redirect

我正在尝试执行301重定向并一次性重写我的URL参数。我一直在这里听一些答案,但无法让它发挥作用。这是我试过的。评论表明我希望它做什么,而不是它实际做了什么。

RewriteEngine on

# Redirect from "/country.php?country=FR&recipe=Croissant" to "/FR/Croissant"
RewriteCond %{THE_REQUEST} ^country\.php/?country=([A-Z]{2})&recipe=(.+) [NC]
RewriteRule ^/%1/$2 [NE,L,R=301]
# Redirect from "/country.php?country=FR" to "/FR"
RewriteCond %{THE_REQUEST} ^country\.php/?country=([A-Z]{2}) [NC]
RewriteRule ^/%1 [NE,L,R=301]

# Internally map "/FR/Croissant" to "/country.php?country=FR&recipe=Croissant"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/([A-Z]{2})/(.+)/?$ country\.php/?country=$1&recipe=$2 [L]
# Internally map "/FR" to "/country.php?country=FR"
RewriteRule ^/([A-Z]{2})/?$ country\.php/?country=$1 [L]

但这不起作用。当我尝试其中一个例子时没有任何事情发生:

/country.php?country=FR&recipe=Croissant停留/country.php?country=FR&recipe=Croissant/FR/Croissant返回404.

我在域的子目录(localhost / food /,localhost / food / index.php和localhost / food / country.php)上运行它,但htaccess文件放在该目录{{1} }。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要修复正则表达式模式和一些语法问题:

RewriteEngine on
RewriteBase /food/

# Redirect from "/country.php?country=FR&recipe=Croissant" to "/FR/Croissant"
RewriteCond %{THE_REQUEST} /country\.php\?country=([A-Z]{2})&recipe=([^&\s]*) [NC]
RewriteRule ^ %1/%2? [NE,L,R=301]

# Redirect from "/country.php?country=FR" to "/FR"
RewriteCond %{THE_REQUEST} /country\.php\?country=([A-Z]{2}) [NC]
RewriteRule ^ %1? [NE,L,R=301]

# ignore rules below for files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Internally map "/FR/Croissant" to "/country.php?country=FR&recipe=Croissant"
RewriteRule ^([A-Z]{2})/(.+?)/?$ country.php?country=$1&recipe=$2 [L,QSA]

# Internally map "/FR" to "/country.php?country=FR"
RewriteRule ^([A-Z]{2})/?$ country.php?country=$1 [L,QSA]

要修复样式,图像等问题,您需要在css,js,images文件中使用绝对路径而不是相对路径。这意味着您必须确保这些文件的路径以http://或斜杠/开头。

或者,您可以在页面HTML的<head>部分下方添加:

<base href="/food/" />

以便从该基本网址解析每个相对网址,而不是从当前网页的网址解析。

相关问题