【问题标题】:PHP Pretty URLs with htaccess without changing the URL带有 htaccess 的 PHP Pretty URLs,无需更改 URL
【发布时间】:2018-09-25 23:28:24
【问题描述】:

我搜索了许多类似的问题,但找不到答案。我有一个有用户的 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

因此用户将始终看到友好的 url,不带问号和 userid= 部分。

我不想将此页面 (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 静默调用特定的漂亮 url。

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

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 天的时间,但找不到解决方案。感谢您对解释规则所做的任何帮助。先感谢您。

【问题讨论】:

    标签: php regex apache .htaccess


    【解决方案1】:

    你可以用这个:

    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

    【讨论】:

      【解决方案2】:

      试试这个,

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

      【讨论】:

        【解决方案3】:

        试试这个 我还没有测试它,但应该可以工作

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

        【讨论】:

        • 您的规则也匹配/profile/index.php,这将导致无限循环错误。
        • 嗨@starkeen,那么它什么时候匹配它以及如何避免它?这是一个大问题吗?谢谢。
        猜你喜欢
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-07
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多