使用目录创建用户友好的 URL

问题描述 投票:0回答:2

我有一个用户注册的页面,他们会被重定向到他们的个人资料。他们的个人资料 URL 为:example.com/profiles/?username=sam,其中 sam 可以是任何名称。这工作成功,但我正在尝试使 URL 更清晰。我想让 URL 看起来像这样:example.com/profiles/sam 这是我的 .htaccess:

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteCond %{THE_REQUEST} /profiles/?\?username=([^&\s]+) [NC]
RewriteRule ^ /profiles/%1? [L,R]
RewriteRule ^(?:profiles/)?([0-9]+)/?$ /profiles/?username=$1 [L]

    SetOutputFilter DEFLATE
    <IfModule mod_setenvif.c>
        # Netscape 4.x has some problems...
        BrowserMatch ^Mozilla/4 gzip-only-text/html

        # Netscape 4.06-4.08 have some more problems
        BrowserMatch ^Mozilla/4\.0[678] no-gzip

        # MSIE masquerades as Netscape, but it is fine
        # BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

        # NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
        # the above regex won't work. You can use the following
        # workaround to get the desired effect:
        BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

        # Don't compress images
        SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
    </IfModule>
    <IfModule mod_headers.c>
        # Make sure proxies don't deliver the wrong content
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
</IfModule>
example.com/profiles/ 中的

profiles 是一个目录。在profiles里面有一个index.php文件,这是创建动态页面的PHP文件。我的 .htaccess 文件位于根文件夹中。我也在使用 GoDaddy。 GoDaddy 指出:“由于启用 mod_rewrite 是在全局级别处理的,因此您无需在 httpd.conf 文件中启用它。您只需将所需的代码添加到 .htaccess 文件的正文中。.htaccess 文件包含重写规则的文件必须与目标文件位于同一目录中。”

使用我的.htaccess,它会将URL从example.com/profiles/?username=sam更改为example.com/profiles/sam,但配置文件根本不显示,而是显示404错误页面,这意味着页面不存在。该页面应该存在。此外,添加 Options +Multiviews 也会产生相同的 404 错误。另外,使用选项+多视图,某些页面显示 CSS 而不是 PHP 页面。

如何才能将 example.com/profiles/?username=sam 重定向到 example.com/profiles/sam 并使个人资料页面实际显示?

apache .htaccess mod-rewrite
2个回答
2
投票

/profile/.htaccess
中制定这样的规则:

RewriteEngine On 
RewriteBase /profiles/

RewriteCond %{THE_REQUEST} /\?username=([^&\s]+) [NC] 
RewriteRule ^ %1? [L,R=302] 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^([^/]+)/?$ index.php?username=$1 [L,QSA] 
  • 您的规则仅匹配
    [0-9]+
    之后的
    /profile/
    ,不会匹配
    sam
  • 要添加
    .php
    ,您应该首先检查它是否存在。

0
投票

我的问题请解决我的网站链接

www.example.com/country/america

我删除中间名“国家”

www.example.com/america

© www.soinside.com 2019 - 2024. All rights reserved.