search
HomeBackend DevelopmentPHP TutorialIn-depth understanding of PHP's .htaccess file_PHP tutorial

The

.htaccess file provides ways to change configurations for each directory.

Working principle and usage

.htaccess file (or "distributed configuration file") provides a method to change the configuration for each directory, that is, placing a file containing instructions in a specific directory, and the instructions in it apply to this directory and all subdirectory.

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

Usually, .htaccess files use the same configuration syntax as the main configuration file. The AllowOverride directive determines which directives in the .htaccess file are valid by category. If a directive is allowed in .htaccess, then in the description of this manual, the directive will have an override section that describes the value that must be set in the AllowOverride directive for the directive to take effect.

(Do not) use .htaccess files

In general, .htaccess files should not be used unless you do not have access to the main configuration file. There is a very common misunderstanding that user authentication can only be achieved through .htaccess files. In fact, this is not the case. It is completely feasible and a good method to write user authentication in the main configuration file.

.htaccess files should be used in situations where the content provider needs to change the server's configuration for a specific directory without root privileges. If the server administrator is unwilling to frequently modify the configuration, he or she can allow users to modify the configuration themselves through the .htaccess file, especially if the ISP runs multiple user sites on the same machine and hopes that users can change the configuration themselves.

However, you should generally avoid using .htaccess files whenever possible. Any configuration that you wish to put in the .htaccess file can be placed in the section of the main configuration file and is more efficient.

There are two main reasons to avoid using .htaccess files.

The first is performance. If AllowOverride enables .htaccess files, Apache needs to look for .htaccess files in every directory, so enabling .htaccess will cause a performance drop regardless of whether it is actually used. In addition, for each request, the .htaccess file needs to be read once.

Also, Apache must look for .htaccess files in all parent directories for all valid directives to take effect (see directives in effect), so if a page in /www/htdocs/example is requested, Apache The following files must be found:

/.htaccess
/www/.htaccess
/www/htdocs/.htaccess
/www/htdocs/example/.htaccess

A total of 4 additional files are accessed, even though none of them exist. (Note that this may simply be due to allowing the root directory "/" to use .htaccess, although this is rare.)

Second is safety. This will allow users to modify the server configuration themselves, which may lead to some unexpected modifications, so please carefully consider whether you should give the user such privileges. However, giving users less privileges than meets their needs will result in additional technical support requests. Therefore, users must be clearly informed of the permissions that have been given to them, explain the value of the AllowOverride setting, and guide them to refer to the corresponding Explain to avoid a lot of trouble in the future.

Note that placing instructions in the .htaccess file in the /www/htdocs/example directory is completely equivalent to placing the same instructions in the section of the main configuration file.

Putting the configuration in the main configuration file is more efficient because it only needs to be read once when Apache starts, rather than every time the file is requested.

Effectiveness of the command

The configuration directives in the .htaccess file apply to the directory where the .htaccess file is located and all its subdirectories. However, it is important to note that there may also be .htaccess files in its upper-level directory, and the directive is to search The order takes effect in sequence, so the instructions in the .htaccess file in a specific directory may override the instructions in the .htaccess file in its parent directory, that is, the instructions in the subdirectory will override the instructions in the parent directory or the main configuration file.

Example: The .htaccess file in the /www/htdocs/example1 directory has the following content: Options +ExecCGI

(Note: "AllowOverride Options" must be set to allow the use of "Options" directives in .htaccess)

The .htaccess file in the /www/htdocs/example1/example2 directory has the following content: Options Includes

Due to the existence of the second .htaccess file, CGI execution in /www/htdocs/example1/example2 is not allowed, but only Options Includes are allowed, which completely overrides the previous settings.

Merge .htaccess into the main configuration file

As discussed in Configuration Sections (Containers), the .htaccess file can override the settings for the corresponding directory in the section, but will also be overridden by other types of configuration sections in the main configuration file. This feature can be used to enforce certain configurations even when AllowOverride is enabled. For example, to force prohibiting script execution in .htaccess but not restrict other situations, you can do this:

<Directory />
Allowoverride All
</Directory>
<Location />
Options +IncludesNoExec -ExecCGI
</Location>

认证举例

如果你只是为了知道如何认证,而直接从这里开始看的,有很重要的一点需要注意,有一种常见的误解,认为实现密码认证必须要使用.htaccess文件,其实是不正确的。把认证指令放在主配置文件的段中是一个更好的方法,而.htaccess文件应该仅仅用于无权访问主配置文件的时候。参见上述关于何时应该与何时不应该使用.htaccess文件的讨论。

有此声明在先,如果你仍然需要使用.htaccess文件,请继续看以下说明。.htaccess文件的内容:

AuthType Basic
AuthName "Password Required"
AuthUserFile /www/passwords/password.file
AuthGroupFile /www/passwords/group.file
Require Group admins

必须设置 AllowOverride AuthConfig 以允许这些指令生效。

服务器端包含(SSI)举例

.htaccess文件的另一个常见用途是允许一个特定的目录使用服务器端包含(SSI),可以在需要的目录中放置.htaccess文件,并作如下配置:

Options +Includes
AddType text/html shtml
AddHandler server-parsed shtml

注意,必须同时设置 AllowOverride Options 和 AllowOverride FileInfo 以使这些指令生效。

CGI举例

可以通过.htaccess文件允许在特定的目录中执行CGI程序,需要作如下配置:

Options +ExecCGI
AddHandler cgi-script cgi pl

另外,如下配置可以使给定目录下的所有文件被视为CGI程序:

Options +ExecCGI
SetHandler cgi-script

注意,必须同时设置 AllowOverride Options 和 AllowOverride FileInfo 以使这些指令生效。

疑难解答

如果在.htaccess文件中的某些指令不起作用,可能有多种原因。

最常见的原因是AllowOverride指令没有被正确设置,必须确保没有对此文件区域设置 AllowOverride None 。有一个很好的测试方法,就是在.htaccess文件随便增加点无意义的垃圾内容,如果服务器没有返回了一个错误消息,那么几乎可以断定设置了 AllowOverride None 。

在访问文档时,如果收到服务器的出错消息,应该检查Apache的错误日志,可以知道.htaccess文件中哪些指令是不允许使用的,也可能会发现需要纠正的语法错误。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752346.htmlTechArticle.htaccess文件提供了针对每个目录改变配置的方法。 工作原理和使用方法 .htaccess文件(或者"分布式配置文件")提供了针对每个目录改变配置的...
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

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
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools