【问题标题】:How to flatten a query string with htacess without affecting how php code如何在不影响 php 代码的情况下使用 htaccess 展平查询字符串
【发布时间】:2014-11-24 23:56:34
【问题描述】:

我想要一个这样的网址

“www.site.com/?u=1”转换成这个“www.site.com/1”

不影响我的 php 脚本。

我还想了解这种转换是如何以及何时在服务器上发生的。

这是我在查询字符串上没有运气的尝试。

Options -Indexes +FollowSymLinks
RewriteEngine On
DirectoryIndex index.php
#////////////Convert 'u' Query String////////////
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?u=$1 [NC]
#/////////////append www before all urls///////////////////////////
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]
#///////////////////remove index.php from url/////////////
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

谢谢。

【问题讨论】:

  • 我假设您网站上的任何网址都是这样的:www.site.com/?u=products/listing。然后,您希望网站将用户重定向到www.site.com/products/listing。我的建议:您应该编辑 php 文件,以便浏览器不会在每次单击链接时通过 htaccess 重定向两次(1 次加载和 1 次重定向)。你想要的只是一个技巧,而不是解决方案。

标签: php .htaccess url url-rewriting query-string


【解决方案1】:

您不希望在重定向之前使用u 规则。这些需要在重定向之后发生:

Options -Indexes +FollowSymLinks
RewriteEngine On
DirectoryIndex index.php

#/////////////append www before all urls///////////////////////////
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

RewriteCond %{THE_REQUEST} \ /+index\.php\?u=([^&\ ]+)
RewriteRule ^ /%1? [L,R=301]

#///////////////////remove index.php from url/////////////
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ )
RewriteRule ^ /%1 [R=301,L]

#////////////Convert 'u' Query String////////////
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?u=$1 [L]

【讨论】:

  • OK 终于成功了,有两个问题,当 index.php 放在地址栏中时,它会重定向到 www.site.com/1 HTTP/1.1 并且再次,它不会直接重定向到 www。 site.com/1,它只返回正确的信息,就像查询字符串 ?u=1 一样。
  • 我们可以在发送 www.site.com/?u=1 时返回 www.site.com/1 吗?
  • 它应该已经这样做了(第二条规则)。您是否清除了浏览器的缓存? 301 重定向被您的浏览器永久缓存
  • 是的,我有,甚至使用不同的浏览器。
  • @Underscore 需要在正则表达式的括号中添加 \
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多