PHP and htaccess redirection: Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz

牧云@^-^@ 提交于 2019-12-24 04:11:34

问题


let's say I want to use .htaccess to rewrite the following.

Rewriting /user.php?username=xyz to /xyz.

I would use:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

The problem is once this is done, how do I access the username in my other links?

so /mike/details.php

How do I get the value of username ('mike') to automatically be added to the URL so it's like: /username/details.php?username=mike

What would I need to change in .htaccess to get this value? Or do I have to do it in the PHP script to parse the URL?

Thanks


回答1:


try this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ user.php?username=$1 [L,QSA]



回答2:


I think passing the username as a query string parameter is not a good solution.

So, make the user data to be stored in the session (server side) and let the session mechanism retrieve it by means of session ID (passed through cookies or GET, it doesn't matter)

Your rewrite rule can still redirect to user.php setting the username parameter, but then user.php will store the user name and its data in the session ... from now every other php script that access the $_SESSION container (invoking session_start()) can easily retrieve every user related data it needs

My 2 cents :)




回答3:


This will overlap with other rules in the site with starts with anytext like say ^abc



来源:https://stackoverflow.com/questions/1136442/php-and-htaccess-redirection-rewriting-yoursite-com-user-phpusername-xyz-to-yo

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