Apache的.htaccess文件配置禁止IP访问、让浏览器缓存图片等文件

方文锋  2026-01-20 20:42:01  18  首页学习

Apache 网站根目录下的【.htaccess】文件 的一些配置


配置1

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ default.php/$1 [QSA,PT,L]
  #RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
  #配置多版本php环境用
  #RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
</IfModule>

<IfModule mod_headers.c>
    #告诉浏览器设置这些格式的文件缓存的时间为90天
    <FilesMatch "\.(png|jpg|jpeg|gif|webp|ico|svg|eot|ttf|woff|woff2|swf|flv|pdf)$">
        Header set Cache-Control "max-age=7776000, public"
    </FilesMatch>
    #告诉浏览器设置这些格式的文件缓存的时间为6小时
    <FilesMatch "\.(js|css)$">
        Header set Cache-Control "max-age=21600, public"
    </FilesMatch>
</IfModule>

配置2:禁止一些IP地址访问网站


#禁止以下IP地址访问
Order Allow,Deny
Allow from all
Deny from 192.168.1.0/24
Deny from 216.118.229.0/24
Deny from 40.74.252.0/24
Deny from 23.248.0.0/16
Deny from 38.6.0.0/16


<IfModule mod_rewrite.c>
    Options +FollowSymlinks -Multiviews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    #RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
    #配置多版本php环境用
    RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1]
</IfModule>

<IfModule mod_headers.c>
    #告诉浏览器设置这些格式的文件缓存的时间为90天
    <FilesMatch "\.(png|jpg|jpeg|gif|webp|ico|svg|eot|ttf|woff|woff2|swf|flv|pdf)$">
        Header set Cache-Control "max-age=7776000, public"
    </FilesMatch>
    #告诉浏览器设置这些格式的文件缓存的时间为6小时
    <FilesMatch "\.(js|css)$">
        Header set Cache-Control "max-age=21600, public"
    </FilesMatch>  
</IfModule> 

<IfModule mod_expires.c> 
    #years months weeks days hours minutes seconds
    ExpiresActive On
    ExpiresDefault "access plus 5 minutes"
    #3个月
    <FilesMatch "\.(png|jpg|jpeg|gif|webp|ico|svg|eot|ttf|woff|woff2|swf|flv|pdf)$">
        ExpiresDefault "access plus 3 months"
    </FilesMatch>
    #6小时
    <FilesMatch "\.(js|css|xml|txt)$">
        ExpiresDefault "access plus 6 hours"
    </FilesMatch>
</IfModule>