手动阀

Good Luck To You!

13个实用的Apache Rewrite重写规则

Apache的mod_rewrite模块允许你通过重写规则来修改URL,从而实现更友好的URL结构、提高SEO效果或增强安全性,以下是13个实用的Apache Rewrite重写规则示例:

13个实用的Apache Rewrite重写规则

1、将HTTP重定向到HTTPS

   RewriteEngine On
   RewriteCond %{HTTPS} off
   RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

2、移除www前缀

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

3、强制使用www前缀

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

4、将动态URL转换为静态URL

   RewriteEngine On
   RewriteRule ^product/([09]+)/?$ product.php?id=$1 [L,QSA]

5、隐藏文件扩展名

13个实用的Apache Rewrite重写规则

   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !f
   RewriteCond %{REQUEST_FILENAME} !d
   RewriteRule ^([^\.]+)$ $1.php [L]

6、将旧域名重定向到新域名

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

7、阻止访问特定文件类型

   RewriteEngine On
   RewriteRule \.(txt|zip)$  [F,L,NC]

8、防止目录遍历攻击

   RewriteEngine On
   RewriteCond %{REQUEST_URI} /\.\./ [OR]
   RewriteCond %{REQUEST_URI} /etc/ [OR]
   RewriteCond %{REQUEST_URI} /bin/ [OR]
   RewriteCond %{REQUEST_URI} /boot/ [OR]
   RewriteCond %{REQUEST_URI} /dev/ [OR]
   RewriteCond %{REQUEST_URI} /lib/ [OR]
   RewriteCond %{REQUEST_URI} /proc/ [OR]
   RewriteCond %{REQUEST_URI} /sbin/ [OR]
   RewriteCond %{REQUEST_URI} /sys/ [OR]
   RewriteCond %{REQUEST_URI} /usr/ [OR]
   RewriteCond %{REQUEST_URI} /var/ [OR]
   RewriteRule ^(.*)$  [F,L]

9、将所有请求重定向到index.php

   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !f
   RewriteCond %{REQUEST_FILENAME} !d
   RewriteRule ^ index.php [L]

10、将查询字符串参数转换为路径信息

13个实用的Apache Rewrite重写规则

    RewriteEngine On
    RewriteCond %{QUERY_STRING} (.*)
    RewriteRule ^(.*)$ $1/%1? [R=301,L]

11、将路径信息转换为查询字符串参数

    RewriteEngine On
    RewriteRule ^(.*)/(.*)$ $1?param=$2 [L,QSA]

12、限制访问特定IP地址

    RewriteEngine On
    RewriteCond %{REMOTE_ADDR} !^123.456\.789\.000$
    RewriteRule ^  [F,L]

13、将多个斜杠替换为单个斜杠

    RewriteEngine On
    RewriteCond %{REQUEST_URI} (.*)//(.*)
    RewriteRule . %1/%2 [R=301,L]

这些规则涵盖了从基本重定向到高级URL重写和安全措施的多种场景,根据具体需求,你可以调整和组合这些规则来实现更复杂的功能。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.7.3

Copyright Your WebSite.Some Rights Reserved.