尝试创建干净的URL,但收到一些错误

时间:2013-10-30 20:49:25

标签: php regex apache .htaccess

我正在尝试从htaccess创建美容网址这是我的代码

AddDefaultCharset UTF-8
RewriteEngine on
RewriteBase /


RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]
RewriteRule (.*)/index$ $1/ [R=301]
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_]+)$ /$1/ [R]
RewriteRule ^([a-zA-Z0-9_]+)/$ /user.php?username=$1

我想显示这样的用户数据,但问题是当我运行像domain.com/contactus这样的任何其他文件时,这会重定向到user.php?username = contactus同样在这个表达式[a-zA-Z0-9_]上我想放(。 )因为像john.dyer这样的用户名这个表达式是正确的 - [a-zA-Z0-9_.]

这是我的user.php

<?php
$username = $_GET["username"];
$data = mysql_query("SELECT * FROM  `users` WHERE  `username` =  '$username'");
$r = mysql_fetch_array($data); 
$query_username                      = $r["username"];

if($query_username == $username)
{
include $_SERVER['DOCUMENT_ROOT'] . '/welcome/index.php';
}
?>

对不起,我对此很新......我正在学习这些东西所以请告诉我是否有更好的方法来做到这一点。感谢

1 个答案:

答案 0 :(得分:1)

你有很多问题,试试这个修改后的代码:

RewriteEngine On

## If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
## If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
## don't do anything
RewriteRule ^ - [L]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]

# remove index.php
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]

RewriteRule ^(.+?)/?$ /user.php?username=$1 [L,QSA]
相关问题