首页 > 解决方案 > 在 php 中如何从 URL 中删除查询字符串以及访问页面的文件名?

问题描述

我有一个网址https://testing.in/show_tmp?tmp=abcval。我想要一个干净的 URL,就像https://testing.in/abcval不破坏网站的功能一样。我的网站是用 Core PHP 构建的。我知道我们可以使用 htacess 文件来实现这一点,但我不知道该怎么做,请帮帮我。

htaccess 文件代码

# DO NOT REMOVE THIS LINE AND THE LINES BELOW SSL_REDIRECT:connectwithme.in
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^connectwithme.in$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]



# DO NOT REMOVE THIS LINE AND THE LINES ABOVE SSL_REDIRECT:connectwithme.in
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/?show_tmp$ [NC]
RewriteRule /?(.+) show_tmp?tmp=$1 [NC,L,QSA]

标签: php.htaccess

解决方案


我们添加了一个关于当前请求 URI 不应包含的重写条件,show_tmp以避免重定向问题。稍后,我们只需捕获请求 URI 并重定向到show_tmp

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/?show_tmp$ [NC]
RewriteRule /?(.+) show_tmp?tmp=$1 [NC,L,QSA,P]

演示: https ://htaccess.madewithlove.be?share=0ddbbf44-57e1-5c9b-9e83-500961e8050d

协助 Anydesk 访问后,您的最终 .htaccess 应如下所示:

# DO NOT REMOVE THIS LINE AND THE LINES BELOW SSL_REDIRECT:connectwithme.in
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^connectwithme.in$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]



# DO NOT REMOVE THIS LINE AND THE LINES ABOVE SSL_REDIRECT:connectwithme.in

#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_URI} !^/?assets/.+$ [NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php !-f #add this for any kind of file extension. If you want to display .html, then you will have to add .html also  
RewriteCond %{REQUEST_URI} !^/?assets/.+$ [NC] 
RewriteCond %{REQUEST_URI} !^/?show_tmp$ [NC] 
RewriteRule (.*) https://%{HTTP_HOST}/show_tmp?tmp=$1 [NC,L,QSA,P]

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

推荐阅读