url rewrite htaccess and php

北城以北 提交于 2019-12-24 10:29:50

问题


I want to rewrite URL and for that I have got following code.

    Options +FollowSymLinks
    RewriteEngine On
    RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?uname=$1
    RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?uname=$1

now when I write url like www.mywebsite.com/username it works fine and not giving any error.

Now how can I get this URL even when I write www.mywebsite.com/index.php?uname=username in hit go.

I want to change www.mywebsite.com/index.php?uname=username to www.mywebsite.com/username when I write www.mywebsite.com/index.php?uname=username in URL.

As rewrite work for prefix of WWW I want same way to change my URL to www.mywebsite.com/username even if user write www.mywebsite.com/index.php?uname=username.


回答1:


The following should work:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ index.php?uname=$1

It will check if the file or directory doesn't exist, and if it doesn't it will assume it's an username and rewrite the URL.

If you want to redirect from index.php?uname=username to /username then you could add this to the top of your index.php:

if (strpos($_SERVER['REQUEST_URI'], "uname") !== false)
{
    header("Location: /" . $_GET['uname']);
}


来源:https://stackoverflow.com/questions/10348472/url-rewrite-htaccess-and-php

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