PHP漂亮的URL与htaccess而不更改URL

时间:2018-04-16 09:16:31

标签: php regex apache .htaccess

我搜索了许多类似的问题,但我找不到答案。我有一个拥有用户的php网站,我想创建用户个人资料页面。

现在,它的工作原理如下:

https://example.com/profile?userid=user_id_here

但我希望它能像这样工作:

https://example.com/profile/user_id_here

当用户点击他们的个人资料网址时,即:

https://example.com/profile/user_id_here

我希望页面以静默方式调用此url:

https://example.com/profile?userid=user_id_here

因此,用户将始终看到没有问号和userid = part的友好网址。

我不想将此页面(https://example.com/profile?userid=user_id_here)重定向到此页面(https://example.com/profile/user_id_here),因为用户不会看到此页面(https://example.com/profile?userid=user_id_here)。

我只是想让profile.php默默地调用特定的漂亮网址。

我目前的重写规则如下,我希望新规则添加以下规则:

RewriteEngine On

# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#remove .php
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

我花了2天多的时间,但我无法找到解决方案。任何帮助解释规则正在做什么是值得赞赏的。先感谢您。

3 个答案:

答案 0 :(得分:0)

试试这个 我没有测试过,但应该工作

RewriteRule ^profile/([^/]*)$ /profile?userid=$1 [L]

答案 1 :(得分:0)

试试这个,

DirectoryIndex index.php
Options +FollowSymLinks 
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

答案 2 :(得分:0)

您可以使用:

RewriteEngine On

# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#remove .php
RewriteRule ^(.+)\.php$ /$1 [R,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,END]

#rewrite /profile/userID to /profile?userid=userID
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^profile/(.+)$ /profile?userid=$1 [L,NC]

RewriteConds确保您不会将现有目录和文件重写为/profile?userid