htaccess文件使用大全
整理自网络ChatGPT产生之内容,文本内容不具备参考意义,程序内容及代码片段有且仅有借鉴意义。
.htaccess文件是一种包含配置信息的文本文件,它可以用来配置Web服务器,从而实现许多各种各样的功能。以下是.htaccess文件使用的一些常见场景:
1. 重定向URL
RewriteEngine On
RewriteRule ^example\.html$ /newexample.html [R=301,L]
上述代码将example.html重定向到newexample.html,同时返回301状态码。
2. 防盗链
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
对于除了example.com之外的所有网站,对访问.png,.jpg,.jpeg和.gif文件的请求将返回403 Forbidden错误。
3. 禁止IP地址
order deny,allow
deny from 192.168.1.1
allow from all
该代码段会拒绝192.168.1.1的所有请求,允许其他请求。
4. 压缩文件
AddOutputFilterByType DEFLATE text/html text/plain text/xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
此代码段使用DEFLATE压缩类型对文本、XML、JavaScript和PHP文件进行压缩。
5. 配置文件缓存
ExpiresActive On
ExpiresByType text/html "access plus 1 hours"
ExpiresByType text/css "access plus 1 months"
ExpiresByType image/gif "access plus 1 years"
ExpiresByType image/jpeg "access plus 1 years"
ExpiresByType image/png "access plus 1 years"
ExpiresByType application/javascript "access plus 1 months"
ExpiresByType application/x-javascript "access plus 1 months"
该代码段配置了文件类型和过期时间。如果浏览器已经缓存了某个与上下文匹配的资源,那么将不会向服务器发出请求,以减少浏览器和服务器之间的流量。
6. 自定义404错误页面
ErrorDocument 404 /404.html
此代码段将自定义404错误页面文件设置为404.html文件,即在无法找到已请求的网页时会自动跳转到404.html页面。
7. 禁用目录列表
Options -Indexes
这个代码片段可以防止Web服务器显示当前目录里的文件列表,因此,当请求的资源不存在时,Web服务器将不会返回目录里的文件列表,而是返回403 Forbidden错误。
这仅仅是.htaccess文件使用的一些例子。几乎可以执行任何脚本任务,就看你怎么使用它了。
Public @ 2023-05-30 12:00:02 整理自网络ChatGPT产生之内容,文本内容不具备参考意义,程序内容有且仅有借鉴意义。