linux apache .htaccess 文件使用

An .htaccess file also known as an hypertext access file is a directory-level configuration file supported by several web servers, used for configuration of site-access issues, such as URL redirection, URL shortening and Access-security control.

An .htaccess file provides various options for website owners to control the server environment variables and other parameters to enhance functionality of their websites. It is placed in the directories and sub-directories of the Apache document root. When you place an .htaccess file in the apache document root, the .htaccess file is detected and executed by the Apache Web Server.

These .htaccess files can be used to alter the configuration of the Apache Web Server to enable and disable additional functionality and features that the Apache Web Server software has to offer. When you are developing a PHP website and working with PHP and Apache, then you can use an .htaccess file for directory level configuration of Apache web server.

You should only use .htaccess files when you don't have root access to the main Apache server configuration file. An .htaccess file provides many features Some of these features include basic redirects, locking outside access to particular files, or more advanced functions such as content password protection or preventing image hotlinking.

However, use of .htaccess files should be avoided when possible. There are two main reasons to avoid the use of .htaccess files.

The first of these is server performance. When AllowOverride is set to allow the use of .htaccess files, httpd will look in every directory for .htaccess files. Thus, permitting .htaccess files causes a performance issue, whether or not you actually even use them! Also, the .htaccess file is loaded every time a document is requested.

In this article, we will look at some different tips and tricks which we can perform with .htaccess file through various examples.

Requirements

  • A server running CentOS-7 on your system.
  • A static IP Address for your server.
  • A non-root user account with sudo privilege set up on your server.

Install Apache

Before you start to work with the .htaccess file, you will need to install Apache server on your system.

To install Apache, run the following command:

sudo yum install httpd -y

After installing Apache, start the Apache service and enable it to start on boot.

You can do this using the following command:

sudo systemctl start httpd.service sudo systemctl enable httpd.service

Now, you need to allow the default Apache port 80 (HTTP) and 443 (HTTPS) using firewalld.

You can do this by running the following commands:

sudo firewall-cmd --permanent --add-port=80/tcp sudo firewall-cmd --permanent --add-port=443/tcp

Now, reload the firewall service for the changes take effect.

sudo firewall-cmd --reload

Enable .htaccess Files

Before you begin, you will need to allow Apache to read .htaccess files located under the /var/www/html directory.

You can do this by editing httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Find the section `` and change AllowOverride None to AllowOverride All

AllowOverride All

Save and exit.

Now restart Apache to put the change into effect:

sudo systemctl restart httpd

How to Use the .htaccess file with Apache

An .htaccess file is a powerful tool for modifying your Apache configuration on a per-domain and even a per-directory level.

An .htaccess file provides a way to make configuration changes on a per-directory basis. If it is placed in a particular document directory then the directives apply to that directory along with all subdirectories below it. So you don't need to change your Apache config file.

In this section, we will learn how to use .htaccess file with Apache using various examples.

Redirect www to non-www

If you want to redirect users from www to a plain non-www domain, it is possible with htaccess. You will need to create .htaccess file in Apache document root directory.

Change directories to your Document root:

cd /var/www/html

Now, create the .htaccess file.

sudo nano .htaccess

add the following content:

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

Save and exit the file.

Now, use curl command to ensure that the www domain redirects to the non-www domain:

curl -I http://www.your-domain.com

You should see the following output:

HTTP/1.1 301 Moved Permanently
Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://your-domain.com/
Content-Type: text/html; charset=iso-8859-1

Redirect non-www to www

Similarly as above, If you want to redirect users from a plain non-www domain to a www domain, add the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

add the following content:

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

Save and exit the file.

Now, use curl command to ensure that the non-www domain redirects to the www domain:

curl -I http://your-domain.com

You should see the following output:

HTTP/1.1 301 Moved Permanently
Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://www.your-domain.com/
Content-Type: text/html; charset=iso-8859-1

Redirect http to https

If you want to redirect your http site to https, add the following content to your .htaccess file.

sudo nano /var/www/html/.htaccess

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Now, save and close.

If you want to redirect only a few pages of your site to https, add the following code to your .htaccess file :

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} page1 [OR]
RewriteCond %{REQUEST_URI} page2 [OR]
RewriteCond %{REQUEST_URI} page3
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Now, save and close.

Redirect https to http

Similarly, if you want to redirect your https site to http, add the following content to your .htaccess file.

sudo nano /var/www/html/.htaccess

RewriteCond %{HTTPS} off
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

Now, save and close.

Redirect All Website Pages

If you want to redirect all pages from domain1.com to domain2.com, add the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

add the following content:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domain1.com$ [OR]
RewriteCond %{HTTP_HOST} ^domain1.com$
RewriteRule ^(.*)$ http://www.domain2.com/$1 [R=301,L]

Save and exit the file.

Now, use curl command to check whether domain redirection working or not:

curl -I http://www.domain1.com

You should get a 301 Moved Permanently response, that shows you new domain redirect location.

Deny File Type Access

If you want to prevent the users accessing a specific file type like index.php and multiple file types like htpasswd, ini, php, sh, and jpeg then add the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

# prevent viewing of a specific file

order allow,deny deny from all

# multiple file types

order allow,deny deny from all

 

Save and exit the file.

Deny visitors by IP address and domains

If you want to block the users from IP 192.168.1.2 and 192.168.1.3, add the following code to your .htaccess file:

sudo nano /var/www/html/.htaccess

Order allow,deny
deny from 255.0.0.0
deny from 255.0.0.1
allow from all

Save and exit the file.

Similarly, you can block users from domain1.com and domain2.com by adding the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

RewriteEngine on
RewriteCond %{HTTP_REFERER} domain1.com [NC,OR]
RewriteCond %{HTTP_REFERER} domain2.com [NC,OR]
RewriteRule .* - [F]

Save and exit the file.

Enable SSI on Websites with .htaccess

SSI also called "Server Side Includes" are directives that are placed in HTML pages, and evaluated on the server while the pages are being served.

While standard HTML files are fine for storing conttent, it is very useful to be able to create some content dynamically. This can be done with SSI.

To do this, you will need to enable them in your .htaccess file. Should you wish to enable it for .html files you need to add the following lines to your .htaccess file:

sudo nano /var/www/html/.htaccess

AddHandler server-parsed .html

Redirect Users to Maintenance Page

If your website is down for maintenance and you want to notify all your users that need to access your websites, then for such cases you can add the following lines to your .htaccess websites that allow only admin access and replace the site pages having links to any .css, .gif, .js etc.

sudo nano /var/www/html/.htaccess

RewriteCond %{REQUEST_URI} !^/admin/ [NC]
RewriteCond %{REQUEST_URI} !^((.*).css|(.*).js|(.*).png) [NC]
RewriteRule ^(.*)$ /ErrorDocs/Maintainence_Page.html
[NC,L,U,QSA]

The above lines check if the requested URL contains any request for any admin page or any request to ".png, .js, .css" pages and for any such requests it replaces that page with "ErrorDocs/Maintainence_Page.html".

Redirect Users to Custom Error Pages

If you want to show custom error pages when a 404 error occurs, then add the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

ErrorDocument 404 /404.php

And you can also extend this for other error pages to:

ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
ErrorDocument 502 /502.html
ErrorDocument 504 /504.html

Save and exit the file.

Use .htaccess to prevent Hacking

If you want to secure your Apache website, you can add the following codes to your .htaccess file to prevent some common hacking techniques by detecting malicious URL patterns.

sudo nano /var/www/html/.htaccess

RewriteEngine On

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

# Block out any script trying to set a mosConfig value through the URL RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]

# Block out any script trying to base64_encode crap to send via URL RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]

# Block out any script that includes a tag in URL RewriteCond %{QUERY_STRING} (|%3E) [NC,OR]

# Block out any script trying to set a PHP GLOBALS variable via URL RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]

# Block out any script trying to modify a _REQUEST variable via URL RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})

# Send all blocked request to homepage with 403 Forbidden error! RewriteRule ^(.*)$ index.php [F,L]

Save and exit the file.

Setting Time Zones

You can use .htaccess file to set the timezone of the Apache server. You can do this by setting a global environment variable ‘TZ’ in the list of global environment variables that are provided by the server to each of the hosted websites for modification.

Add the following lines to your .htaccess file to set the timezone of the Server.

sudo nano /var/www/html/.htaccess

SetEnv TZ Australia/Melbourne

Save and exit the file.

Conclusion

In this tutorial, we have explained how to work with the .htaccess file including various examples. I hope you find it easy to work with the .htaccess file in the future and can successfully use it to secure and optimize your web server in production environment.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值