首页 > 解决方案 > 将一些参数添加到 url 作为目录,但指向带有查询参数的原始 url

问题描述

如果有人点击此网址,我想要:

https://sk.carpul.eu/search?t=0&fp=Bratislava&fla=48.1486&fln=17.1077&tp=Zvolen&tla=48.5762&tln=19.1371&sdate=&stime=&p=1&qh=4b9873ddfb

它将在 url 中有不错的位置,并将搜索重命名为 spolujazda 为:

https://sk.carpul.eu/spolujazda/Bratislava/Zvolen/?t=0&fp=Bratislava&fla=48.1486&fln=17.1077&tp=Zvolen&tla=48.5762&tln=19.1371&sdate=&stime=&p=1&qh=4b9873ddfb

但是服务器仍然会指向:

https://sk.carpul.eu/search?t=0&fp=Bratislava&fla=48.1486&fln=17.1077&tp=Zvolen&tla=48.5762&tln=19.1371&sdate=&stime=&p=1&qh=4b9873ddfb

我在htaccess中试过:

# check if the actual request if for "this1"
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /search\.php\?fp=([^&]+)&tp=([^&\ ]+)
# redirect to "this2"
RewriteRule ^ spolujazda/%1/%2/? [R=301,L,NE]

# now rewrite "this2" back to "this1"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?search/([^/]+)/([^/]+)/?$ /search.php?fp=$1&tp=$2 [L,QSA]

但不工作。

对于 .php 删除,我在 htaccess 的开头有这个:

Options +FollowSymlinks
RewriteEngine On


## hide .php extension
# To internally forward /dir/file to /dir/file.php
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

标签: .htaccessurl-rewriting

解决方案


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

RewriteEngine On

# check if the actual request if for "this1"
RewriteCond %{THE_REQUEST} /search(?:\.php)?\?(?:.*&)?fp=([^&]+).*&tp=([^&\s]+) [NC]
# redirect to "this2"
RewriteRule ^ /spolujazda/%1/%2/ [R=301,L,NE]

# now rewrite "this2" back to "this1"
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(?:spolujazda|search)/([^/]+)/([^/]+)/?$ /search.php?fp=$1&tp=$2 [L,QSA]

推荐阅读