简体   繁体   中英

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.

For example:

Someone is trying to access 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 .

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 . 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=' .

I think this piece of code will solve you problem, and helps you to understand a few things with htaccess rules:

# 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文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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