【问题标题】:.htaccess - Replace hyphen (dash) '-' with a foward slash '/'.htaccess - 将连字符(破折号)“-”替换为正斜杠“/”
【发布时间】:2014-11-26 17:06:21
【问题描述】:

我在使用 .htaccess 时遇到问题

这个时候我有这样的事情:

http://example.com/page-example?getVariable=1234

但我想要类似的东西:

http://example.com/page/example/1234

我尝试使用 .htacces 将连字符替换为斜线

Options +FollowSymlinks -MultiViews
RewriteRule ^([^/]+)-([^/]+).php/?$ /$1/$2 [R,L]

我得到了这样的东西

 http://example.com/page/example?getVariable=1234

但是服务器找不到路径,我想是因为它承认'page'是一个文件夹。

我该怎么做,但服务器在根文件夹中搜索文件“page-example.php”而不是在“/page/”中搜索“example.php”?

PS:我已经在使用下面的代码来删除 .php 扩展名和“www”。来自网址。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

【问题讨论】:

  • 你的意思是page-example.php? 吗?另外,我不经常使用rewrite,但你不是倒着做rewrite吗?
  • 我对重写规则也不太了解,但是你说的倒退是什么意思?
  • 你的重写器是先做实际的路径而不是最后,但乔恩林给出了一个相当全面的答案。

标签: php regex apache .htaccess mod-rewrite


【解决方案1】:

在你已有的规则之前,尝试添加:

RewriteCond %{THE_REQUEST} \ /+page-([^/]+)(?:\.php|)\?getVariable=([^&\ ]+)
RewriteRule ^ /page/%1/%2? [L,R]

RewriteRule ^page/([^/]+)/([^/]+)$ /page-$1.php?getVariable=$2 [L,QSA]

所以整个事情看起来像:

RewriteEngine on

RewriteCond %{THE_REQUEST} \ /+page-([^/]+)(?:\.php|)\?getVariable=([^&\ ]+)
RewriteRule ^ /page/%1/%2? [L,R]

RewriteRule ^page/([^/]+)/([^/]+)$ /page-$1.php?getVariable=$2 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

【讨论】:

  • 这很奇怪,它并没有改变 URL 中的任何内容,仍然是 example.com/page-example?getVariable=1234 但同样感谢您的帮助!
  • 谢谢!它就像一个魅力!我不知道为什么它在本地主机上不起作用(我有 mod_rewrite 活动),我认为这是因为它在所有这些之前有另一条路径。它是“localhost/site/page/example”,但在我的网站中,从 de 根文件夹开始,它运行良好!还有一件事:你认为这是一个友好的 URL 吗?我的意思是,“example.com/page/example/1234”而不是“example.com/page-example?getVariable=1234”?
猜你喜欢
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多