Home  >  Article  >  Backend Development  >  Detailed explanation of apache .htaccess file and summary of configuration techniques

Detailed explanation of apache .htaccess file and summary of configuration techniques

PHP中文网
PHP中文网Original
2016-08-18 09:15:421957browse

1. The basic function of .htaccess

.htaccess is a plain text file, which stores instructions related to Apache server configuration.
    .htaccess’s main functions include: URL rewriting, custom error pages, MIME type configuration and access control, etc. Mainly reflected in pseudo-static applications, image hotlink protection, custom 404 error pages, blocking/allowing specific IPs/IP segments, directory browsing and homepages, prohibiting access to specified file types, file password protection, etc. E The scope of the use of .htaccess is mainly for the current directory.

2. Enable .htaccess configuration
To enable .htaccess, you need to modify httpd.conf, enable AllowOverride, and use AllowOverride to limit the use of specific commands.
Open the httpd.conf file with a text editor and search

Copy the code as follows:

<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
改为:
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>

If you need to use a file name other than .htaccess, you can use the AccessFileName command to change it. For example, if you need to use .config, you can configure it in the server configuration file as follows:

Copy the code as follows:

AccessFileName .config

Three. .htaccess access control

1. Access control basics: Order command

​​​​​ Restrict users from accessing some key directories, usually by adding .htaccess files. The common writing method is as follows:

Copy the code as follows:

<Files  ~ "^.*\.([Ll][Oo][Gg])|([eE][xX][eE])">
 Order allow,deny
 Deny from all
</Files>

Description:

(1) The wavy line after Files indicates that "regular expressions" are enabled. Simple writing is: 073204447274641b4c6ff9450252faeb.

(2) Order command: Through the Allow, Deny parameters, Apache first finds and applies the Allow command, and then applies the Deny command to block all access. Deny, Allow can also be used.

4. URL rewriting

The following is an example of a simple URL rewriting rule:

Copy the code as follows:

# Turn on RewriteEngine mode
RewriteEngine On
# Please do not modify the Rewrite system rules
RewriteRule ^p /([0-9]+).html$ index.php?post_id=$1
RewriteRule ^u-(username|uid)-(.+).html$ space.php?$1=$2

Among them, RewriteEngine Indicates turning on URL rewriting, and RewriteRule is the rewriting rule.

5. Configure the error page

The basic syntax is as follows:

Copy code The code is as follows:

# custom error documents
ErrorDocument 401 /err/401.php
ErrorDocument 403 /err/403.php
ErrorDocument 404 /err/404.php
ErrorDocument 500 /err/500.php

6. htaccess common commands and configuration techniques

1. Suppress the display of directory lists
Sometimes, for some reason , there is no index file in your directory, which means that when someone types the path to the directory in the browser address bar, all files in the directory will be displayed, which will leave security risks for your website.
To avoid this (without having to create a bunch of new index files), you can type the following command in your .htaccess document to prevent
the directory listing from being displayed:

Copy the code as follows:

Options -Indexes

2. Block/allow specific IP addresses
In some cases, you may only want to allow users with certain IPs to access your website (for example: only allow users with a specific ISP to enter a certain directory ), or want to block certain IP addresses (for example: to isolate low-level users from your information page). Of course, this only works if you know the IP address you want to block, however most users online these days use dynamic IP addresses, so this is not a common method of limiting usage.
You can use the following command to ban an IP address:

Copy the code as follows:

deny from 000.000.000.000

The 000.000.000.000 here is the banned IP address. If you only specify a few of them, Then you can block the address of the entire network segment. If you enter 210.10.56., all IP addresses from 210.10.56.0 to 210.10.56.255 will be blocked.
You can use the following command to allow an IP address to access the website:

Copy the code as follows:

allow from 000.000.000.000

The allowed IP address is 000.000.000.000. You can allow the entire IP address just like banning it. network segment.
If you want to prevent everyone from accessing this directory, you can use:

Copy the code as follows:

deny from all

However, this does not affect the script's use of documents in this directory.
3. Replace the index file
Maybe you don’t want to always use index.htm or index.html as the index file of the directory. For example, if your site uses PHP files, you might want to use index.php serves as the index document for this directory. Of course you don't have to be limited to the "index" document, if you want, using .htaccess you can even set foofoo.balh as your index document!
These mutually replacing index files can be arranged in a list, and the server will search from left to right to check which document exists in the real directory. If none are found, it will display the directory listing (unless you have turned off showing directory file listings).

Copy the code as follows:

DirectoryIndex index.php index.php3 messagebrd.pl index.html index.htm


4.重定向(rewrite)
.htaccess 最有用的功能之一就是将请求重定向到同站内或站外的不同文档。这在你改变了一个文件名称,但仍然想让用户用旧地址访问到它时,变的极为有用。另一个应用(我发现的很有用的)是重定向到一个长URL,例如在我的时事通讯中,我可以使用一个很简短的URL来指向我的会员链接。以下是一个重定向文件的例子:

复制代码代码如下:

Redirect /location/from/root/file.ext http:    ///new/file/location.xyz


上述例子中,访问在root目录下的名为oldfile.html可以键入:

复制代码代码如下:

/oldfile.html
访问一个旧次级目录中的文件可以键入:

/old/oldfile.html


你也可以使用.htaccess重定向整个网站的目录。假如你的网站上有一个名为olddirectory的目录,并且你已经在一个新网站http: ///newdirectory/上建立了与上相同的文档,你可以将旧目录下所有的文件做一次重定向而不必一一声明:

复制代码代码如下:

Redirect /olddirectory http: ///newdirectory


这样,任何指向到站点中/olddirectory目录的请求都将被重新指向新的站点,包括附加的额外URL信息。例如有人键入:


http: ///olddirecotry/oldfiles/images/image.gif
请求将被重定向到:

http: ///newdirectory/oldfiles/images/image.gif


如果正确使用,此功能将极其强大。

 

七、安全配置
下面的htaccess代码能够提高你的web服务器的安全水平。图片链接盗用保护非常有用,它能防止其他人偷盗使用你的服务器上的图片资源。
1. 通过.htaccess放盗链
痛恨那些偷盗链接你的web服务器上的图片资源而耗尽了你的带宽的行为吗?试试这个,你可以防止这种事情的发生。

复制代码代码如下:

RewriteBase /  
RewriteCond %{HTTP_REFERER} !^$  
RewriteCond %{HTTP_REFERER} !^http://(www.)?php.cn/.*$ [NC]  
RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]


2. 防黑客
如果你想提高网站的安全等级,你可以去掉下面的几行代码,这样可以防止一些常见恶意URL匹配的黑客攻击技术。

复制代码代码如下:

RewriteEngine On  
# proc/self/environ? 没门!  
RewriteCond %{QUERY_STRING} proc/self/environ [OR]  
# 阻止脚本企图通过URL修改mosConfig值  
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]  
# 阻止脚本通过URL传递的base64_encode垃圾信息  
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]  
# 阻止在URL含有<script>标记的脚本  
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]  
# 阻止企图通过URL设置PHP的GLOBALS变量的脚本  
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]  
# 阻止企图通过URL设置PHP的_REQUEST变量的脚本  
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})  
# 把所有被阻止的请求转向到403禁止提示页面!  
RewriteRule ^(.*)$ index.php [F,L]


3. 阻止访问你的 .htaccess 文件或者指定类型的文件
下面的代码可以阻止别人访问你的.htaccess文件。同样,你也可以设定阻止多种文件类型。

# 保护你的 htaccess 文件  
<Files .htaccess>  
order allow,deny  
deny from all  
</Files>  
# 阻止查看指定的文件  
<Files secretfile.jpg>  
order allow,deny  
deny from all  
</Files>  
# 多种文件类型  
<FilesMatch “.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>  
 Order Allow,Deny  
Deny from all  
</FilesMatch>[/code]

4.禁止脚本执行,加强你的目录安全

复制代码代码如下:

# 禁止某些目录里的脚本执行权限  
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi  
Options -ExecCGI

 


八、一些常用的设置
1.时区设置
有些时候,当你在PHP里使用date或mktime函数时,由于时区的不同,它会显示出一些很奇怪的信息。下面是解决这个问题的方法之一。就是设置你的服务器的时区。你可以在这里找到所有支持的时区的清单。
1.SetEnv TZ Australia/Melbourne 
2. seo/seo.html" target="_blank">搜索引擎友好的301永久转向方法
为什么这是搜索引擎友好的呢?因为现在很多现代的搜索引擎都有能根据检查301永久转向来更新它现有的记录的功能。

复制代码代码如下:

Redirect 301 http:    //www.php.cn/article/index http:    //www.php.cn/article/


3. 屏蔽下载对话框
通常,当你下载东西的时候,你会看到一个对话框询问你是保持这个文件还是直接打开它。如果你不想看到这个东西,你可以把下面的一段代码放到你的.htaccess文件里。

复制代码代码如下:

AddType application/octet-stream .pdf  
AddType application/octet-stream .zip  
AddType application/octet-stream .mov


4. 省去www前缀
SEO的一个原则是,确保你的网站只有一个URL。因此,你需要把所有的通过www的访问转向的非www,或者反这来。

复制代码代码如下:

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


5. 个性化Error页面
对每个错误代码定制自己个性化的错误页面。

复制代码代码如下:

ErrorDocument 401 /error/401.php  
ErrorDocument 403 /error/403.php  
ErrorDocument 404 /error/404.php  
ErrorDocument 500 /error/500.php


6. 压缩文件
通过压缩你的文件体积来优化网站的访问速度。

复制代码代码如下:

# 压缩 text, html, javascript, css, xml:  
AddOutputFilterByType DEFLATE text/plain  
AddOutputFilterByType DEFLATE text/html  
AddOutputFilterByType DEFLATE text/xml  
AddOutputFilterByType DEFLATE text/css  
AddOutputFilterByType DEFLATE application/xml  
AddOutputFilterByType DEFLATE application/xhtml+xml  
AddOutputFilterByType DEFLATE application/rss+xml  
AddOutputFilterByType DEFLATE application/javascript  
.AddOutputFilterByType DEFLATE application/x-javascript


7. 缓存文件
缓存文件是另外一个提高你的网站访问速度的好方法。

复制代码代码如下:

<FilesMatch “.(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf)$”>  
Header set Cache-Control “max-age=2592000″  
</FilesMatch>


8. 对某些文件类型禁止使用缓存
而另一方面,你也可以定制对某些文件类型禁止使用缓存。

复制代码代码如下:

# 显式的规定对脚本和其它动态文件禁止使用缓存  
<FilesMatch “.(pl|php|cgi|spl|scgi|fcgi)$”>  
Header unset Cache-Control  
</FilesMatch>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn