使用php变量重写和重定向

时间:2017-05-15 17:46:55

标签: .htaccess mod-rewrite url-rewriting

我只是想自动重写:

来自: mysite.com/channel.php?id=BBC&name=British Broadcasting Company &date=today

收件人: mysite.com/channel-britishbroadcastingcompany-today.html

我尝试过:

RewriteRule ^channel-(.*)-(.*)\.html$ /channel.php?id=1&name=$2&date=$3 [R]

但没有任何反应。

4 个答案:

答案 0 :(得分:3)

希望这个最简单的人会帮助你。如果

,这将重定向
  

1。 REQUEST_URI/channel.php

     

2。 QUERY_STRING符合此模式id=something&name=something&date=something

将此重定向到/channel-%1-%2.html此处

  

1。 %1将保留name参数的值

     

2。 %2将保留date参数的值

RewriteEngine on
Options -MultiViews

RewriteCond %{REQUEST_URI} ^/channel\.php$
RewriteCond %{QUERY_STRING} id=.*?&name=(.*?)&date=(.*)
RewriteRule .* /channel-%1-%2.html? [R=301]

根据OP指定redirect上基于某些html page query parameters的第一个previous page网址的要求,然后在RewriteEngine on Options -MultiViews RewriteCond %{REQUEST_URI} ^/channel\.php$ RewriteCond %{QUERY_STRING} id=.*?&name=(.*?)&date=(.*) RewriteRule .* /channel-%1-%2? [R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} ^/channel\-(.*?)\-(.*?) RewriteRule .* /channel.php? [L] 上重写请求。所以.htaccess的完整代码就是这样的。

REQUEST_FILENAME

添加的第二部分的说明。

  

1。 REQUEST_URI如果文件不存在为文件和目录。

     

2. channel-somewords-somewords如果request_uri以这种模式开始/channel.php

然后在fifth

上重写请求

答案 1 :(得分:1)

如果我正确理解了问题,那么您目前有一个文件 channel.php ,您想要实现的目标是获得更多"友好"浏览器位置栏中的搜索引擎优化和一般美学的URL,但仍然有channel.php处理您的请求。

如果确实如此,则需要双向重写。 首先,您需要获取原始URL并将其重定向到新的漂亮版本。 其次,你需要在内部重写这个漂亮的URI,然后仍然将它提供给幕后的channel.php。

RewriteEngine On
RewriteBase /

# This part rewrites channel.php?name=X&date=Y into channel-X-Y.html
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{QUERY_STRING} (.*\&)?name=([^&]+)\&date=([^&]+)(?:\&(.*))?
RewriteRule ^channel.php$ channel-%2-%3.html?%1%4 [R,L,NE]

# This part rewrites it back into channel.php but keeps the "friendly" URL visible
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^channel-(.*)-(.*).html$ channel.php?name=$1&date=$2 [L,QSA]
  • 请注意,第一个规则集将重写限制为方法GET - 否则您将丢失任何提交的POST数据。
  • 它还允许任何其他查询字符串参数包围 name date (其余的查询字符串参数将传递给.html URI然后将被channel.php选中。
  • 另请注意 ENV:REDIRECT_STATUS 规则 - 这是至关重要的,如果没有该部分,您将陷入重定向循环。

答案 2 :(得分:0)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^([a-z0-9-_.]+)/?$ index.php?id=$1 [NC,L]
RewriteRule ^([a-z0-9-_.]+)/([a-z0-9]+)/?$ index.php?id=$1&goto=$2 [NC,L]

它要做的是检查index.php并将其替换为site/dir/index.phpsite/dir/namehere之类的内容,而不是index.php,你可以使用explode()来分隔当前url ang的值得到变量

答案 3 :(得分:0)

我假设您要求重写,虽然您在当前规则中使用重定向标记,并且还假设BBC在id变量中是静态的,然后尝试使用下面的,

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^channel-([^/]+)-([^/]+).html$ channel.php?id=BBC&name=$1&date=$2 [L]