Change URL in browser without redirection with htaccess

此生再无相见时 提交于 2019-12-13 17:07:07

问题


I've looked everywhere to find the proper solution/method but I can't seem to find anything that works for me. I even asked friends and they helped but none prevailed.

What i'm trying to do is, changing the URL displayed in the browser but only that. (No rediraction, page re-loading). I want to do this to make my UCP just cleaner looking when going through certain pages/files.

What am I trying to achieve? Heres an example on a profile, the URL would be:

mysite.com/ucp/profile.php?player=Heartfire

However, I want it to look like

mysite.com/ucp/profile/heartfire

Or something else! I just want to get rid of the parameters AFTER the .PHP

I've tried various examples found with google and this website but none seems to work, could somebody please guide me along the way to achieve the result.

what have I tried so far? Here are a few examples of what I tried before:

RewriteRule ^profile/([0-9]+)/?$    /ucp/profile.php?player=$1
RewriteRule profile.php?player=$1 profile.php [NC,L]
RewriteRule ^profile$ profile.php?player=$1

So what am I doing wrong that it isn't working?


回答1:


Put the following in .htaccess file inside website's root directory:

RewriteEngine On

RewriteCond %{THE_REQUEST} ^GET\ /ucp/profile\.php?([^=]+)=(\S+) [NC]
RewriteRule ^ucp/profile\.php$ /ucp/%1/%2? [R=301,L,NC]

# Now, deal with internal rewrites (which will not cause redirection):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ucp/([^/]+)/([^/]+)/?$ /ucp/profile.php?$1=$2 [NC,L]



回答2:


You can use internal redirects what will not change your url but map your request as your wanted.

What you want is impossible because:

Htaccess and rewrite is at server side. The request arrived to the server, need to rewrite at serverside and you need to change it in the clients url bar.

To achieve this the server should send a redirect with the url what you expected. This ia why redirect is mandatory. Server can't rewrite clients urls, just can send a redirect response.

Internal redirect can simulate you something like the request was what you expected but it is transparent at for the clients.

Btw, permanent redirect is the right solution here to notify the user and give the chance to let them know the resource has been changed and update the bookmark / api / whatever.



来源:https://stackoverflow.com/questions/32912814/change-url-in-browser-without-redirection-with-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!