zoukankan      html  css  js  c++  java
  • .htaccess重写规则

    .htaccess基本语法和应用
    .htaccess是Apache服务器的一个非常强大的分布式配置文件。
    正确的理解和使用.htaccess文件,可以帮助我们优化自己的服务器或者虚拟主机。
    如何启用htaccess
    以windows为例,进入apache/conf目录,找到httpd.conf文件,去掉
    LoadModule rewrite_module modules/mod_rewrite.so
    前面的#,然后设置目录属性AllowOverride All,重启apache即可
    常见格式
    下面是一个典型的htaccess文件
    # 开启URL重写
    RewriteEngine on
    # URL重写的作用域
    RewriteBase /path/to/url
    # 满足怎样的条件
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    # 应用怎样的规则
    RewriteRule .? http://www.example.com%{REQUEST_URI} [R=301,L]
    来看看RewriteCond,首先有一个%,因为{HTTP_HOST}是一个apache变量,需要用%来指示。从!开始就是匹配的条件,支持 正则。!表示不等于,这句话的意思就是:如果HTTP_HOST不是www.example.com。后面的[NC](no case)表示忽略大小写,常见的还有
    [L](last):终止一系列的RewriteCond和RewriteRule
    [R](redirect):触发一个显示的跳转,也可以指定跳转类型,如[R=301]
    [F](forbidden):禁止查看特定文件,apache会触发403错误
    典型应用
    图片防盗链
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/ [NC]
    RewriteRule \.(gif|jpg|png)$ - [F]
    由于是基于HTTP_REFERER的验证,所以只能防止一般的图片盗链,因为HTTP_REFERER是比较容易伪造的
    自定义404错误页面
    如果用户输入了一个不存在的url,那么就显示自定义的错误页面
    ErrorDocument 404 /404.html
    # 其他同理
    ErrorDocument 500 /500.html
    处理移动过的文件
    Redirect 301 /old.html http://yoursite.com/new.html
     
    # 也可以是下面这样
    RewriteRule /old.html http://yoursite.com/new.html [R=301,L]
     
    # 如果想隐式跳转(URL地址不变,但实际上内容是其他URL的),就使用下面的
    RewriteRule /old.html http://yoursite.com/new.html [L]
    对于RewriteRule还有好多文章可以做,比如
     
    # 把html后缀的url链接到php文件
    # $1指代的是前面第1个用括号括起来的内容
    RewriteRule ^/?([a-z/]+)\.html$ $1.php [L]
    # 或者把旧文件夹的内容链接到新文件夹
    RewriteRule ^/?old_directory/([a-z/.]+)$ new_directory/$1 [R=301,L]
     
    # 隐藏文件名
    RewriteRule ^/?([a-z]+)$ $1.php [L]
    禁止显示目录列表
    如果目录里没有index文件,又没有对该目录做过特别的处理,尤其是windows主机,那么该目录里的内容就会显示出来,这时可以在根目录创建 一个.htaccess文件,然后写上
    Options -Indexes
    # 就这么一句就搞定了
    阻止/允许特定IP/IP段
    # 禁止所有IP,除了指定的
    order deny,allow
    deny from all
    # 如果想允许IP段,如123.123.123.0 ~ 123.123.123.255,则
    # allow from 123.123.123.
    allow from 123.123.123.123
     
    ErrorDocument 403 /page.html
     
    <Files page.html>
    allow from all
    </Files>
     
    #如果想禁止特定IP
    deny from 123.123.123.123
    添加MIME类型
    AddType video/x-flv .flv
    # 如果设置类型为 application/octet-stream 将提示下载
    AddType application/octet-stream .pdf
  • 相关阅读:
    002-pythn基础-循环、编码
    001-python3 初识
    confluence6.x安装
    python+ffmpeg切割视频
    Elasticsearch6.x和Kibana6.x的安装
    django基础
    CDH的完全离线安装(ubuntu16)
    python之旅十【第十篇】paramiko模块
    解决 MariaDB无密码就可以登录的问题
    切割日志(mysql,nginx,php tomcat)使用logrotate
  • 原文地址:https://www.cnblogs.com/loveyouyou616/p/2831957.html
Copyright © 2011-2022 走看看