SoFunction
Updated on 2025-04-10

Detailed explanation and configuration skills of Apache pseudostatic (Rewrite).htaccess file

1. The basic function of htaccess

.htaccess is a plain text file that stores instructions related to Apache server configuration. The main functions of .htaccess include: URL rewriting, custom error pages, MIME type configuration, and access permission control. It is mainly reflected in pseudo-static applications, image anti-theft links, custom 404 error pages, blocking/allowing specific IP/IP segments, directory browsing and home pages, prohibiting access to specified file types, file password protection, etc. The scope of use of .htaccess is mainly aimed at the current directory.

2. Enable .htaccess configuration

Enable .htaccess, need to be modified, enableAllowOverride, and can be usedAllowOverrideRestrict the use of specific commands. After opening the file with a text editor, search

<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>

Change to:

<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>

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

AccessFileName .config

3. .htaccess access control

1. Access control basics: Order command In order to restrict users from accessing some key directories, .htaccess files are usually added. The common writing method is as follows:

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

Note: (1) The wavy line after Files means that "regular expression" is enabled. The simple writing method is: <Files *>. (2) Order command: Through the Allow and Deny parameters, Apache first finds and applies the Allow command, and then applies the Deny command to block all accesses. You can also use Deny and Allow.

4. URL rewriting

Here is a simple example of URL rewriting rules:

# Turn on RewriteEngine modeRewriteEngine On
# Rewrite system rules do not modifyRewriteRule ^(.*)\.html$ $ [NC]
RewriteRule ^article/([0-9]+)\.html$ ?id=$1
RewriteRule ^u-(username|uid)-(.+)\.html$ ?$1=$2

in,RewriteEngineIndicates that URL rewriting is enabled.RewriteRuleIt is the rewrite rule. If there is a page like:

http:///?id=12&page=3 // Original linkhttp:///category/12/3  // Rewrite it into

use:

RewriteRule ^category/([0-9]+)/([0-9]+)$  ?id=$1&page=$2

RewriteRule matches the new link Original link; When applying the replacement, the matching content in the previous() is referenced with $1 afterwards, and the matching content in the second() is referenced with $2,,,,,,,,,,$Match the end of the string, other characters Please see the regular expression symbol definition.

5. Configuration error page

The basic syntax is as follows:

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

6. Common commands and configuration techniques for htaccess

1. Disable the display of directory lists

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

Options -Indexes

2. Block/allow specific IP addresses

In some cases, you may want to allow users of certain specific IPs to access your website (for example, only users using specific ISPs to access a directory), or you may want to block certain specific IP addresses (for example, isolate low-level users from your information layout). Of course, this is only useful if you know the IP address you want to intercept, however, most users on the Internet now use dynamic IP addresses, so this is not a common way to restrict usage. You can block an IP address using the following command:

deny from 000.000.000.000

Here, 000.000.000.000 is the banned IP address. If you only specify a few of them, you can block the address of the entire network segment. If you enter 210.10.56., all IP addresses of 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:

allow from 000.000.000.000

The allowed IP address is 000.000.000.000.000. You can allow the entire network segment just like blocking the IP address. If you want to block everyone from accessing the directory, you can use:

deny from all

However, this does not affect the script program's use of the documents in this directory.

3. Replace index file

Maybe you don't want to use or as an index file for the directory all the time. For example, if your site uses PHP files, you might want to use as an index document for that directory. Of course, there is no need to be limited to the "index" document. If you want, use .htaccess you can even set it as your index document! These index files that are replaced 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 one is not found, it will display the directory list (unless you have turned off the display directory file list).

DirectoryIndex  index.php3   

4. Redirect (rewrite)

One of the most useful features of .htaccess is to redirect requests to different documents on or off the site. This becomes extremely useful when you change a file name but still want the user to access it with the old address. Another app (which I found useful) is to redirect to a long URL, for example in my newsletter I could use a very short URL to point to my affiliate link. Here is an example of a redirect file:

Redirect /location/from/root/ http://new/file/

In the above example, accessing the name under the root directory can be typed:

/

To access a file in an old secondary directory, you can type:

/old/

You can also use .htaccess to redirect directories of the entire website. If you have a directory called olddirectory on your website and you have created the same document as above on a new website http://newdirectory/, you can redirect all files in the old directory without having to declare them one by one:

Redirect /olddirectory http://newdirectory

In this way, any requests to the /olddirectory directory in the site will be redirected to the new site, including additional URL information. For example, someone typed:

http://olddirecotry/oldfiles/images/

The request will be redirected to:

http://newdirectory/oldfiles/images/

If used correctly, this feature will be extremely powerful.

7. Security configuration

The followinghtaccessCode can improve the security level of your web server. Image link theft protection is very useful, it prevents others from stealing image resources on your server.

1. Use .htaccess to release the chain

Do you hate those behaviors that steal links image resources on your web server and exhaust your bandwidth? Try this, you can prevent this from happening.

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

2. Anti-hacking

If you want to increase the security level of your website, you can remove the following lines of code, which can prevent some common malicious URL matching hacking techniques.

RewriteEngine On
# proc/self/environ? No way!RewriteCond %{QUERY_STRING} proc/self/environ [OR]

# Block scripts from attempting to modify mosConfig value through URLRewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]

# Block the base64_encode spam information that scripts are passed through URLsRewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]

# Block scripts containing <script> tags in URLsRewriteCond %{QUERY_STRING} (&lt;|%3C).*script.*(&gt;|%3E) [NC,OR]

# Scripts that attempt to set PHP's GLOBALS variables through URLsRewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]

# Scripts that attempt to set PHP's _REQUEST variable through URLRewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})

# Turn all blocked requests to the 403 prohibition prompt page!RewriteRule ^(.*)$  [F,L]

3. Block access to your .htaccess file or file of the specified type

The following code can prevent others from accessing your .htaccess file. Similarly, you can also set blocking multiple file types.

# Protect your htaccess file&lt;Files .htaccess&gt;
order allow,deny
deny from all
&lt;/Files&gt;

# Block viewing of specified files&lt;Files &gt;
order allow,deny
deny from all
&lt;/Files&gt;

# Multiple file types&lt;FilesMatch “.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”&gt;
Order Allow,Deny
Deny from all
&lt;/FilesMatch&gt;[/code]

4. Prohibit script execution and enhance your directory security

# Prohibit script execution permissions in certain directoriesAddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI

8. Some commonly used settings

1. Time zone settings

Sometimes, when you use date or mktime functions in PHP, it will display some very strange information due to the time zone. Here is one of the solutions to this problem. It is to set the time zone of your server. You can find a list of all supported time zones here. TZ Australia/Melbourne 2. seo/" target="_blank">

2. Search engine-friendly 301 permanent steering method

Why is this search engine friendly? Because many modern search engines now have the ability to update their existing records based on check 301 permanently.

Redirect 301 ///home ///

3. Block the download dialog box

Usually, when you download something, you will see a dialog asking you whether to keep the file or open it directly. If you don't want to see this, you can put the following code into your .htaccess file.

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

4. Eliminate the www prefix

One principle of SEO is to make sure your website has only one URL. Therefore, you need to turn all access to non-www, or reverse it.

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

5. Personalized Error Page

Customize your own personalized error page for each error code.

ErrorDocument 401 /error/
ErrorDocument 403 /error/
ErrorDocument 404 /error/
ErrorDocument 500 /error/

6. Compress files

Optimize website access speed by compressing your file size.

# Compress 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. Cache files

Caching files is another great way to increase access to your website.

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

8. Disable cache for certain file types

On the other hand, you can also customize the use of cache for certain file types.

# Explicitly stipulate that cache is prohibited for scripts and other dynamic files&lt;FilesMatch “.(pl|php|cgi|spl|scgi|fcgi)$”&gt;
Header unset Cache-Control
&lt;/FilesMatch&gt;

Note ([NC][L][R][F] in htaccess file):

  • NC: no case, case insensitive, case ignoring;
  • L: last, indicating that it is the last rule, and the .htaccess file parsing will exit;
  • R: redirect, redirect;
  • F: forbidden, access is prohibited.

The above is the detailed explanation and configuration skills of Apache pseudostatic (Rewrite).htaccess file. For more information on the detailed explanation of Apache pseudostatic (Rewrite) configuration, please pay attention to my other related articles!