πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ EspaΓ±ol | πŸ‡΅πŸ‡Ή PortuguΓͺs | πŸ‡ΉπŸ‡­ ΰΉ„ΰΈ—ΰΈ’ | πŸ‡¨πŸ‡³ δΈ­ζ–‡

A Complete Guide to .htaccess: How to Use Redirects, URL Rewriting, and Access Control

In this series so far, we've built a solid foundation in server administration, from the basics of Apache to installation, configuration with `httpd.conf`, and running multiple sites with virtual hosts. You've done great work! Now, it's time for the final installment in our Apache series. This time, we'll do a deep dive into the "magic file" that is your strongest ally in website management: .htaccess.

"I want to forward a specific page to a new URL," "I want to make my URLs short and beautiful," "I want to password-protect a specific directory"... this one file can grant all these wishes of a website operator. In this article, we'll introduce everything from the basic usage of .htaccess to practical configuration examples, complete with code you can copy and paste right away. Once you master this article, your site management will become much more free and powerful!


What is .htaccess? The Absolute Basics

.htaccess is a configuration file that allows you to finely control the server's behavior on a per-directory (folder) basis where Apache is running. If `httpd.conf` is the law of the entire country, then `.htaccess` is like a local ordinance that applies only to a specific region. Its greatest appeal is the ability to apply unique rules on a site-by-site or even folder-by-folder basis without touching the main server configuration.

The Golden Rule for Enabling .htaccess

To use `.htaccess`, you must have permission to override settings for that directory. This is configured in the `<Directory>` block for the target directory within your `httpd.conf` or virtual host configuration file (`httpd-vhosts.conf`).

Please confirm that the line AllowOverride All is present. If it's set to None, anything you write in your `.htaccess` file will be ignored until you change it to All and restart Apache.

<Directory "/path/to/your/site">
    # This setting needs to be "All"
    AllowOverride All
    Require all granted
</Directory>

As long as this setting is in place, you're all set. Just create a file named `.htaccess` with a text editor and upload it to the directory where you want the rules to apply.


1. Redirection: Guiding Users to a Different Page

Redirection is a feature that automatically forwards access from an old URL to a new URL, which is essential when moving a site or changing a page's URL. It's also extremely important from an SEO perspective.

Redirecting a Specific Page

This is the simplest form of redirection. It forwards access from `old.html` to the new `new.html`. The "301" indicates that this is a "permanent" redirect, which tells search engines that the URL has moved for good.

Redirect 301 /old.html http://www.example.com/new.html

2. URL Rewriting: Making URLs Beautiful with mod_rewrite

mod_rewrite is a particularly powerful module within Apache that allows you to rewrite URLs behind the scenes. This makes it possible for the URL the user sees to remain beautiful, while the server processes it as a different URL internally.

To use mod_rewrite, you first need to declare that you're going to use the rewrite engine.

RewriteEngine On

Unifying "www vs. non-www"

This unifies the URL to the `www.example.com` version, regardless of whether it's accessed with or without the "www." This is a very effective setting for SEO to avoid splitting your site's reputation.

RewriteEngine On
# If the accessed hostname is 'example.com'
RewriteCond %{HTTP_HOST} ^example\.com$
# Permanently redirect the entire URL to 'www.example.com'
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

Forcing HTTPS: Forcing http access to https

From a security standpoint, always-on SSL (https communication) is now a must for websites. This automatically forwards any access via http to https.

RewriteEngine On
# If the connection is not https
RewriteCond %{HTTPS} off
# Redirect the entire URL to the same path on https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Making Dynamic URLs Look Static

For example, this makes a URL with parameters like `example.com/user.php?id=123` look like a simple and clean URL, `example.com/user/123`.

RewriteEngine On
# If the URL is in the format 'user/number'
RewriteRule ^user/([0-9]+)/?$ /user.php?id=$1 [L]

This setting allows users to continue using a beautiful URL, while making it easier for developers to handle data with parameters.


3. Access Control: Locking Down Specific Areas

You can apply password protection (Basic Authentication) to a directory that you only want to allow certain people to view, such as a members-only page.

Setting Up Basic Authentication

Basic Authentication requires two files: `.htaccess` and `.htpasswd`, which contains the password. First, place an `.htaccess` file with the following content in the directory you want to lock.

AuthType Basic
# The message to display in the authentication dialog
AuthName "Secret Area"
# Specify the location of the file with usernames and passwords
AuthUserFile /path/to/.htpasswd
# Allow access only to valid, authenticated users
Require valid-user

Important: The path to `.htpasswd` specified in `AuthUserFile` must be in a secure location that is not accessible from the web (outside the document root).


Creating the .htpasswd File

Next, create the `.htpasswd` file, which stores usernames and encrypted passwords. This is typically generated using the `htpasswd` command-line tool on the server.

When creating a user for the first time (use the `-c` option to create a new file):

htpasswd -c /path/to/.htpasswd user1

When adding a second user or more (do not use `-c`):

htpasswd /path/to/.htpasswd user2

When you run the command, you will be prompted to enter a password. After you enter it, the `.htpasswd` file will be created or updated at the specified path.


Other Useful Configuration Examples

Displaying Custom Error Pages

When an error like "404 Not Found" occurs, this allows you to display a custom-designed page instead of the server's plain error page.

ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html

Denying Access from Specific IP Addresses

This blocks annoying traffic or access from specific IP addresses.

Require all granted
Require not ip 123.45.67.89
Require not ip 192.168.1.0/24

Conclusion

Great work! This concludes our 4-part series on Apache. In this final installment, we learned about some of the powerful features of `.htaccess`, the file that provides a solution for all those "nice-to-have" settings in website management.

`.htaccess` is incredibly deep, and what we've introduced here is just one small example. However, by applying the basics you've learned today, you can achieve all sorts of control, limited only by your ideas. Please try out various settings, experience them "working," and feel how convenient it is.

By understanding what goes on behind the scenes of a web server, your skills as a web creator should have gained even more depth. We hope your web development life ahead is even more fun and creative!