【问题标题】:Using htaccess to redirect user profiles使用 htaccess 重定向用户配置文件
【发布时间】:2015-05-16 19:58:06
【问题描述】:

我正在创建一个社交网站。使用 .htaccess 我已成功从 url 中删除 .php 扩展名,但我无法将 domain.com/u.php?username=[username] 重定向到 domain.com/u/[用户名]。以下是我的 .htaccess 文件:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

DirectoryIndex home.php

我在 stackoverflow 中看到了很多示例和代码,但它们都从 domain.com/user.php?username=[username] 重定向到 domain.com/[username]。但这会影响我的网站,因为我已经删除了 .php 扩展名,我可能最终会出现名称冲突。提前致谢。

【问题讨论】:

    标签: php apache .htaccess mod-rewrite redirect


    【解决方案1】:

    你可以把这段代码放在你的root htaccess中

    DirectoryIndex home.php
    Options -MultiViews
    
    RewriteEngine On
    RewriteBase /
    
    # redirect /u.php?username=XXX to /u/XXX
    RewriteCond %{THE_REQUEST} \s/u\.php\?username=([^&\s]+)\s [NC]
    RewriteRule ^ u/%1? [R=301,L]
    
    # hide php extension (if file exists)
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteCond %{THE_REQUEST} \s/(.+)\.php(?:\?|\s) [NC]
    RewriteRule ^ %1? [R=301,L]
    
    # internally rewrite /u/XXX to /u.php?username=XXX
    RewriteRule ^u/([^/]+)$ u.php?username=$1 [L]
    
    # internally rewrite (if it exists) extensionless to php extension
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
    RewriteRule ^(.+)$ $1.php [L]
    

    【讨论】:

    • 这很好,但我遇到了一个问题。页面内容未正确加载:(
    • 这是正常行为,因为您创建了一个虚拟目录 (/u/) 并且您使用 relative 路径而不是 absolute 路径你的html资源。为所有资源链接添加前导斜杠或在<head> 之后添加此标记:<base href="/">
    • 你能给我看一个你的链接的例子吗?比如css之类的
    • 原来是:<link rel="stylesheet" href="assets/globals/plugins/blueimp-gallery/css/blueimp-gallery.min.css">,但是我按照你说的<link rel="stylesheet" href="/assets/globals/plugins/blueimp-gallery/css/blueimp-gallery.min.css">改了,但是还是不行
    • 哦,对了,您没有提到您的项目在子文件夹中。我猜你调整了 htaccess 代码,因为它不应该用于子文件夹。无论如何,您必须在每个资源链接之前添加“/myproject/”,或者(如果您不想替换所有链接)您可以在<head> html 标记之后添加<base href="/myproject/">
    猜你喜欢
    • 2012-03-01
    • 2015-10-07
    • 2020-12-16
    • 1970-01-01
    • 2021-08-03
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多