【问题标题】:htaccess Replace spaces and dots with a dashhtaccess 用破折号替换空格和点
【发布时间】:2016-08-10 00:30:35
【问题描述】:

好的,我的 htaccess 代码已经完成了一定程度的工作……现在我被困住了。

这里是原始网址:

example.com/search/store_info.php?store=113&dentist=Dr.%20John%20Doe

我想要实现的是一个干净的 URL,没有像这样的点/句点或空格 (%20):

example.com/search/113/dr-john-doe

但是,使用我当前使用的 htaccess 代码,我得到了以下结果:

example.com/search/113/dr.

医生的姓名是从数据库中提取的,每个“博士”后面都有一个点 (.),因此从某种意义上说,这是流程停止的地方。我猜是因为点?

这是我拥有的 htaccess 代码:

RewriteEngine On

RewriteBase /search/

RewriteCond %{THE_REQUEST} /store_info\.php\?store=([a-z0-9]+)&dentist=  ([a-z0-9]+) [NC]
RewriteRule ^ %1/%2/? [R=301,L]

RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/?$ store_info.php?store=$1&dentist=$2 [QSA,L,NC]

【问题讨论】:

  • 错误的做法。您的网页首先应该只包含干净的网址,然后您将它们转换回“丑陋”的网页以供内部使用。
  • @MarcB 如果我不使用 htaccess 代码,我正在尝试生成干净的 URL,它看起来像 example.com/search/store_info.php?store=113&dentist=Dr.%20John%20Doe 但我提供的 htaccess 代码会截断牙医的全名点
  • @anubhava 当我将其推送到现场时,该代码可以在我这边运行...但是它显示的 URL 为 example.com/search/113/dr.,而不是医生的全名。
  • 你确定dentist=后面有空格吗?
  • @anubhava 当我在dentist= 之后添加空格时,它会引发错误,但是,如果没有空格,则 URL 有效,但它只显示example.com/search/113/dr. 而不是这个example.com/search/113/dr-john-doe 你知道吗我是说?

标签: apache .htaccess mod-rewrite url-rewriting


【解决方案1】:

您可以使用这些规则:

Options -MultiViews
RewriteEngine On    
RewriteBase /search/

# redirect internal URL to pretty URL
RewriteCond %{THE_REQUEST} /store_info\.php\?store=([a-z0-9]+)&dentist=([^\s&]+) [NC]
RewriteRule ^ %1/%2/? [L,NE,R=301]

# skip all files and directories from rules below
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# recursive rule to repeatedly convert DOT or space to hyphen
RewriteRule ^([a-z0-9]+)/([^\s.]*)[.\s]+(.*)$ $1/$2-$3 [NC,DPI,E=DONE:1]

# after all the hyphen conversion is done do a redirect
RewriteCond %{ENV:DONE} =1
RewriteRule ^([0-9a-z]+)/([^\s.]+)$ $1/$2 [R=301,NE,L]

# internally rewrite pretty URL to actual one
RewriteRule ^([a-z0-9]+)/([a-z0-9-]+)/?$ store_info.php?store=$1&dentist=$2 [QSA,L,NC]

【讨论】:

  • 啊啊啊这么近!这段代码在一定程度上有效......它有效,因为它抓住了整个名字,但是,是否可以让医生的名字在名字之间出现破折号?如:dr-john-doenot 像这样 drjohndoe 破折号最终会替换通常在 URL 中的“%20”
  • 好的,URL 可以正常显示,例如:dr-john-doe 但是,现在页面坏了...没有显示 css 或图像,我使用了 如上一个问题的其他答案之一所述
  • 好的,我尝试了您提供的基本代码,但得到了同样的结果……没有任何显示。即使我使用<base href="/">,原始代码也能正常工作,并允许所有图像和 CSS 工作,是的,我清除了缓存并在私人浏览器窗口中尝试了它。
  • 是的,它在您上面的代码中提供...我复制了所有代码并将其实现到我的 htaccess 文件中。你提供的代码在<IfModule mod_rewrite.c></IfModule>里面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 2012-12-25
  • 2013-12-11
相关资源
最近更新 更多