【发布时间】:2016-06-28 21:40:23
【问题描述】:
我有一个用户注册的页面,他们会被重定向到他们的个人资料。他们的个人资料 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 是一个目录。内部配置文件是一个 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 错误。同样使用 Options +Multiviews,一些页面显示 CSS 而不是 PHP 页面。
如何才能将 example.com/profiles/?username=sam 重定向到 example.com/profiles/sam 并使个人资料页面实际显示?
【问题讨论】:
-
[R]表示客户端重定向,这意味着您正在重写然后将客户端重定向到新的 url。您的服务器上没有“物理”/profiles/johndoe.php 页面,因此您最终会生成 404。客户端在浏览器中看到的 url 应该始终是友好的,然后您的重写翻译那些友好/公共网址进入“丑陋”的内部网址。你重写的方向是另一个方向。 -
@MarcB 这很有意义,但我该如何实现呢?如何向客户端显示用户友好的 URL,但在内部我将友好的 URL 翻译成丑陋的?
-
您总是发送像
<a href="/profiles/johndoe.php">这样的html,然后您的重写将其转换为内部/foo/bar/profile.php?johndoe.php。重写纯粹是内部的,并且客户端永远不会看到内部唯一/丑陋的 url。
标签: php apache .htaccess mod-rewrite