【问题标题】:hiding get variable in url在 url 中隐藏获取变量
【发布时间】:2013-09-27 01:28:21
【问题描述】:

我有一个类似

的网址
localhost/index?id=2

如何使用 htaccess 隐藏 id 部分并只显示:

localhost/index/2

【问题讨论】:

  • 大多数人想要localhost/index/2localhost/2
  • @Dagon 不管是什么都没关系我只想摆脱id=
  • @Prix 不适合我。

标签: php .htaccess url-rewriting get


【解决方案1】:

为了捕获查询字符串,您需要使用%{QUERY_STRING}%{THE_REQUEST}

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\?id=([^&\s]+) [NC]
RewriteRule ^ /index?%1 [R=302,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

鉴于您没有其他可能与您的需求冲突的规则,这应该可以正常工作。

一旦您确认其工作正常,您可以从 302 更改为 301,但为了避免缓存,应始终使用 302 完成测试。

使用%{THE_REQUEST} 的另一种方式是这样的:

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

# Redirect /index?id=2 to /index/2
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\?id=([^&\s]+) [NC]
RewriteRule ^ /index/%1? [R=302,L]

# Internally forward /index/2 to /index.php?id=2
RewriteRule ^index/([0-9]+)/?$ /index.php?id=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

【讨论】:

  • 我在 .htaccess 中有RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php ,当我添加你的代码时它不起作用。我仍然看到完整的网址。
  • @Lmxc 查看我在上面发布的第一条规则的更新,试试看。我已经用您的规则对其进行了测试,当您访问 http://localhost/index?id=200 时它会正常工作,它会更改为 http://localhost/index?200
  • 现在 id 没有通过 url 传递。我将id 设为空。
  • @Lmxc 因为您要求将其删除,为了立即获取它,您需要使用 PHP 中的 stackoverflow.com/a/8469777/342740 或者如果您希望可以使用第二个示例更改 URL,该示例将通过id回来就好了。
  • @Lmxc 因为您使用的是相对路径,例如 <link rel="stylesheet" type="text/css" href="css/my.css"> 并且相对路径假定 css 文件夹位于 URL 的最近文件夹中,在这种情况下它变为 /index/css/my.css为了避免这种情况,您需要使用像 <link rel="stylesheet" type="text/css" href="http://localhost/css/my.css"> 这样的绝对路径,图像、JavaScript 等也是如此。
【解决方案2】:
 RewriteEngine On
 RewriteRule    ^([A-Za-z0-9-+_%*?]+)/?$    index.php?id=$1     [L]

([A-Za-z0-9-+_%*?]+)

简而言之,您要的是 ([in here]+) 并且不止一个,但是如果您删除括号后的 + 符号,它将仅返回第一个字符

【讨论】:

  • 你能把你的.htaccess文件的代码给我检查一下解决问题吗
猜你喜欢
  • 2011-04-08
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
相关资源
最近更新 更多