【问题标题】:Need help regarding htaccess pretty url需要有关 htaccess 漂亮网址的帮助
【发布时间】:2019-02-05 13:26:54
【问题描述】:

我的.htaccess 文件:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

RewriteRule ^([a-zA-Z0-9-]+)$ index.php?page=$1 [QSA,L]
RewriteRule ^([a-zA-Z0-9-]+)/$ index.php?page=$1 [QSA,L]

我在 URL 中定义了一个键,即“页面”,它工作正常。现在我需要包含第二个键,但每个页面的“键”都会不同。

例如:

  • example.com/index.php?page=user?id=john

  • example.com/index.php?page=product?url=product-url

需要将它们转换为:

  • example.com/user/john

  • example.com/product/product-url

如何根据页面定义单独的第二个键?

【问题讨论】:

  • 没有你想要的例子,很难回答!
  • 添加了一个例子,希望现在对你更清楚
  • 可能只是一个拼写错误,但由于您两次犯了同样的错误,因此可能值得澄清...您只能在 URL 中包含一个 ?。因此,/index.php?page=user?id=john 显然应该是 /index.php?page=user&id=john(对于您的其他示例也是如此)。此外,您应该真正决定您的 URL 是否以斜杠结尾,而不是同时允许两者(这可能是“重复内容”并且不利于 SEO)。如果您必须然后重定向一个到另一个。

标签: .htaccess mod-rewrite friendly-url


【解决方案1】:

你可以使用:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

RewriteRule ^user/([^/]+)/?$ index.php?page=user&id=$1 [NC,QSA,L]
RewriteRule ^product/([^/]+)/?$ index.php?page=product&url=$1 [NC,QSA,L]
RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?page=$1 [QSA,L]

【讨论】:

  • 是的,这会加载数据,但指向 css、js 和图像的链接会中断。
  • url-example.com/css/custom.css,,变成example.com/user/css/custom.css
  • 在你的页面中使用绝对链接(/ 之前),/css/custom.css 或在 html 头部添加 <base href="/">。这是无法避免的,因为通过重写,您更改了根目录的位置
猜你喜欢
  • 2012-03-07
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 2012-01-10
  • 2012-06-05
  • 2012-06-08
  • 2016-06-23
  • 1970-01-01
相关资源
最近更新 更多