Php 在url中隐藏get变量

Php 在url中隐藏get变量,php,.htaccess,url-rewriting,get,Php,.htaccess,Url Rewriting,Get,我有一个像 localhost/index?id=2 如何使用htaccess隐藏id部分并仅显示: localhost/index/2 ([A-Za-z0-9-+\%*?]+)为了捕获查询字符串,您需要使用%{query\u string}或%{the\u REQUEST}: Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / # Redirect /index?id=2 to /index/2 Rewr

我有一个像

localhost/index?id=2
如何使用htaccess隐藏id部分并仅显示:

localhost/index/2

([A-Za-z0-9-+\%*?]+)为了捕获查询字符串,您需要使用
%{query\u string}
%{the\u 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]

大多数人想要
localhost/index/2
localhost/2
@Dagon不管它是什么,我只想摆脱
id=
@Prix对我不起作用。你能把你的.htaccess文件的代码放进去让我检查一下吗解决问题我有
重写引擎在RewriteCond%{REQUEST\u FILENAME}-d RewriteCond%{REQUEST_FILENAME}\.php-f RewriteRule^(.*)$$1.php
in.htaccess,当我添加代码时,它不起作用。我仍然可以看到完整的url。@Lmxc看到我在上面发布的第一条规则的更新,试试看。我已经用您的规则对其进行了测试,当您访问
http://localhost/index?id=200
它变为
http://localhost/index?200
。现在,
id
没有通过url传递。我得到的
id
为空。@Lmxc是因为您要求删除它,为了现在就得到它,您需要从PHP中使用它,或者如果您希望可以使用第二个示例更改URL,它会很好地将id传回。@Lmxc是因为您使用的是相对路径,例如,对于相对路径,它假设css文件夹位于URL最近的文件夹上。在本例中,它变成了
/index/css/my.css
,为了避免这种情况,您需要使用绝对路径,如
,图像、JavaScript等也是如此。
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]