简体   繁体   English

使用htaccess重定向/重写

[英]Redirect/rewrite with htaccess

I just started learning about .htaccess , and i can't seem to understand how to redirect to a url ,when the current url doesn't contain something in it and/or is not like it suppose to be. 我刚刚开始学习.htaccess,并且当当前URL中不包含某些内容和/或看起来不像时,我似乎无法理解如何重定向到该URL。

For example: 例如:

Someone is trying to access www.example.com/contact.php . 有人试图访问www.example.com/contact.php。 But my htaccess says that every url that is not www.example.com or doesn't contain '?page='(www.example.com/index.php?page=contact.php) , should be changed into www.example.com . 但是我的htaccess表示,每个非www.example.com或不包含'?page ='(www.example.com/index.php?page=contact.php)的网址,都应更改为www.example .com。

Also this checking must be before this: 同样,此检查必须在此之前:

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

So whenever , the user types example.com , it will be redirected to www.example.com . 因此,只要用户输入example.com,它将被重定向到www.example.com。 In case it writes example.com/contact.php or www.example.com/contact.php , it will be redirected to www.example.com , because it is not www.example.com neither contains '?page=' . 如果它写example.com/contact.php或www.example.com/contact.php,它将被重定向到www.example.com,因为它不是www.example.com,也不包含'?page ='。

I think this piece of code will solve you problem, and helps you to understand a few things with htaccess rules: 我认为这段代码将解决您的问题,并帮助您了解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]

您会尝试吗,通过htaccess将动态链接转换为搜索引擎可读链接的网站真棒, 转换为htaccess文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM