【问题标题】:Redirect/rewrite with htaccess使用 htaccess 重定向/重写
【发布时间】:2015-10-18 17:45:48
【问题描述】:

我刚开始学习 .htaccess ,我似乎无法理解如何重定向到一个 url ,当当前 url 不包含任何内容和/或不像它假设的那样。

例如:

有人试图访问 www.example.com/contact.php 。但是我的 htaccess 说每个不是 www.example.com 或不包含 '?page='(www.example.com/index.php?page=contact.php) 的网址都应该更改为 www.example .com。

此检查必须在此之前:

RewriteEngine On
        RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
        RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

因此,每当用户键入 example.com 时,它将被重定向到 www.example.com。如果它写入 example.com/contact.php 或 www.example.com/contact.php ,它将被重定向到 www.example.com ,因为它不是 www.example.com 也不包含 '?page=' 。

【问题讨论】:

  • 你的 htaccess 没有说你提到的任何事情。如图所示,如果 host 不是 www.example.com,它会将任何 URL 重定向到 www.example.com。资源/index.php与主机地址不同
  • @arco444 ,正如我所说....我刚开始学习 1 小时前,我很困...
  • 如果我理解,您想检查文件是否存在(例如contact.php),如果不存在,请重定向到主页?
  • @zessx ,不,我想检查 url 是像 www.example.com 还是像 www.example.com/index.php?page=contact.php ,换句话说,如果它包含 '?page=' (这个子字符串在我的应用程序中是静态的)。如果当前的 url 和这 2 个一样,那么没关系,但如果不是,那么它应该重定向到 www.example.com 。例如,如果有人访问 www.example.com/contact.php ,它没有通过条件,所以它会被重定向。

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

我认为这段代码会解决你的问题,并帮助你理解 htaccess 规则的一些事情:

# Active rewrite engine
RewriteEngine On

# Force www.
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

# If it's the homepage
RewriteCond %{REQUEST_URI} ^/?$
# Skip the next 4 rules (self-inclusion)
RewriteRule .* - [S=4]

# If url is not "index.php"
RewriteCond %{REQUEST_URI} !^/index.php [OR]
# Or does not contain "page="
RewriteCond %{QUERY_STRING} !(^|&)page=.+(&|$)
# Redirect to homepage
RewriteRule . /? [L,R=301]

【讨论】:

  • 抱歉这么晚才回答,我试过你的例子,但它不起作用,它进入一个循环,顺便说一下,网址 www.example.com/index.php 应该重定向也到 www.example.com ,所以第一个条件不好。如果是 www.example.com 或 www.example.com/index.php?page=contact.php ,则 url 有效。 (如果包含 '?page=' ,字符串)。
  • 没关系,我设法让它工作,只是改变了一些东西,但你的代码正是我想要的,非常感谢。
【解决方案2】:

你要不要试试这个,通过htaccess Convert to htaccess file将动态链接转换为搜索引擎可读链接的网站真的很棒

【讨论】:

  • 很好的分享,太好了!! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多