在htaccess中将重写规则将查询字符串转换为斜杠php

时间:2017-04-18 09:52:23

标签: php apache .htaccess mod-rewrite

好的我已经尝试了多种解决方案,但仍然无法实现。所以我需要做的是

mydomain.com/search?q=product&l=london

mydomain.com/search/product/london

基本上我使用重写规则通过遵循此代码来隐藏.php扩展名

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

现在,search.php转换为搜索和用户搜索时。它重定向到尾部斜杠而不是查询字符串

这是我到目前为止所使用的

RewriteCond %{THE_REQUEST} /search/?q=([^&]+)&l=([^\s]+) [NC]
RewriteRule ^ /%1/%2? [NC,L,R]

#skip the rule if the request is for dir
RewriteCond %{REQUEST_FILENAME} !-d

 #skip the rule if the request is for file
 RewriteCond %{REQUEST_FILENAME} !-f
 #rewrite any other request  to "/packagemenu.php?"
 RewriteRule ^([^/]+)/([^/]+)/?$ /search?q=$1&l=$2 [NC,L]

RewriteBase /search/

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

RewriteCond %{THE_REQUEST} /search(?:\.php)?\?q=([^\s&]+)\s [NC]
RewriteRule ^ search/%1/? [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# internal forward from pretty URL to actual one
RewriteRule ^search/([^/]+)/?$ search?q=$1 [NC,L,QSA]

RewriteRule ^search/([^/]+)/([^/]+)/?$ search?q=$1&l=$2 [NC,L,QSA]

但他们两个都不起作用。我没有太多的知识,所以请帮帮我。

3 个答案:

答案 0 :(得分:2)

让您的网站以.htaccess为根:

Options -MultiViews
RewriteEngine On
RewriteBase /jobportal/

# To externally redirect /search.php?q=product&l=london to /search/query/london/
RewriteCond %{THE_REQUEST} /search(?:\.php)?\?q=([^\s&]+)&l=([^\s&]+)\s [NC]
RewriteRule ^ search/%1/%2/? [R=301,L,NE]

# To externally redirect /search.php?q=product to /search/query/
RewriteCond %{THE_REQUEST} /search(?:\.php)?\?q=([^\s&]+)\s [NC]
RewriteRule ^ search/%1/? [R=301,L,NE]

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

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

# internal forward from /search/product/ to search.php?q=product
RewriteRule ^search/([^/]+)/?$ search.php?q=$1 [NC,L,QSA]

# internal forward from /search/product/london/ to search.php?q=product&l=london
RewriteRule ^search/([^/]+)/([^/]+)/?$ search.php?q=$1&l=$2 [NC,L,QSA]

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

答案 1 :(得分:1)

您可以使用mydomain.com/search/product/london中的以下规则来获取网址.htaccess

RewriteEngine On
RewriteRule ^search/([^/]*)/([^/]*)$ /search?q=$1&l=$2 [L]

在测试之前,请确保清除缓存。

答案 2 :(得分:1)

尝试以下,

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/search$
RewriteCond %{QUERY_STRING} ^q=([^\/]+)&l=([^\/]+)$
RewriteRule ^ search/%1/%2? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Rewriterule ^search/([^\/]+)/([^\/]+)$ search.php?q=$1&l=$2 [QSA,L]