search
HomeBackend DevelopmentPHP TutorialDetailed explanation of apache .htaccess file and summary of configuration techniques

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: .

(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
图文详解apache2.4+php8.0的安装配置方法图文详解apache2.4+php8.0的安装配置方法Dec 06, 2022 pm 04:53 PM

本文给大家介绍如何安装apache2.4,以及如何配置php8.0,文中附有图文详细步骤,下面就带大家一起看看怎么安装配置apache2.4+php8.0吧~

Linux apache怎么限制并发连接和下载速度Linux apache怎么限制并发连接和下载速度May 12, 2023 am 10:49 AM

mod_limitipconn,这个是apache的一个非官方模块,根据同一个来源ip进行并发连接控制,bw_mod,它可以根据来源ip进行带宽限制,它们都是apache的第三方模块。1.下载:wgetwget2.安装#tar-zxvfmod_limitipconn-0.22.tar.gz#cdmod_limitipconn-0.22#vimakefile修改:apxs=“/usr/local/apache2/bin/apxs”#这里是自己apache的apxs路径,加载模块或者#/usr/lo

apache版本怎么查看?apache版本怎么查看?Jun 14, 2019 pm 02:40 PM

查看​apache版本的步骤:1、进入cmd命令窗口;2、使用cd命令切换到Apache的bin目录下,语法“cd bin目录路径”;3、执行“httpd -v”命令来查询版本信息,在输出结果中即可查看apache版本号。

超细!Ubuntu20.04安装Apache+PHP8环境超细!Ubuntu20.04安装Apache+PHP8环境Mar 21, 2023 pm 03:26 PM

本篇文章给大家带来了关于PHP的相关知识,其中主要跟大家分享在Ubuntu20.04 LTS环境下安装Apache的全过程,并且针对其中可能出现的一些坑也会提供解决方案,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。

nginx,tomcat,apache的区别是什么nginx,tomcat,apache的区别是什么May 15, 2023 pm 01:40 PM

1.Nginx和tomcat的区别nginx常用做静态内容服务和代理服务器,直接外来请求转发给后面的应用服务器(tomcat,Django等),tomcat更多用来做一个应用容器,让javawebapp泡在里面的东西。严格意义上来讲,Apache和nginx应该叫做HTTPServer,而tomcat是一个ApplicationServer是一个Servlet/JSO应用的容器。客户端通过HTTPServer访问服务器上存储的资源(HTML文件,图片文件等),HTTPServer是中只是把服务器

php站用iis乱码而apache没事怎么解决php站用iis乱码而apache没事怎么解决Mar 23, 2023 pm 02:48 PM

​在使用 PHP 进行网站开发时,你可能会遇到字符编码问题。特别是在使用不同的 Web 服务器时,会发现 IIS 和 Apache 处理字符编码的方法不同。当你使用 IIS 时,可能会发现在使用 UTF-8 编码时出现了乱码现象;而在使用 Apache 时,一切正常,没有出现任何问题。这种情况应该怎么解决呢?

如何在 RHEL 9/8 上设置高可用性 Apache(HTTP)集群如何在 RHEL 9/8 上设置高可用性 Apache(HTTP)集群Jun 09, 2023 pm 06:20 PM

Pacemaker是适用于类Linux操作系统的高可用性集群软件。Pacemaker被称为“集群资源管理器”,它通过在集群节点之间进行资源故障转移来提供集群资源的最大可用性。Pacemaker使用Corosync进行集群组件之间的心跳和内部通信,Corosync还负责集群中的投票选举(Quorum)。先决条件在我们开始之前,请确保你拥有以下内容:两台RHEL9/8服务器RedHat订阅或本地配置的仓库通过SSH访问两台服务器root或sudo权限互联网连接实验室详情:服务器1:node1.exa

【总结】apache调用不起来php5.6的原因和解决方法【总结】apache调用不起来php5.6的原因和解决方法Mar 28, 2023 pm 03:00 PM

PHP5.6和Apache是Web开发中最常用的工具之一。然而,有时候,当我们尝试调用PHP5.6时,会遇到一些问题,例如无法调用PHP文件或页面等等。在本文中,我将探讨为什么您可能无法调用PHP5.6以及如何解决这个问题。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software