Force HTTPS jump: judge non-HTTPS requests through RewriteCond and permanently redirect to HTTPS with R=301; 2. Remove file extensions: use !-f and !-d conditions to rewrite as /about as /about.php; 3. Force www or without www: match through HTTP_HOST and jump 301 to unified domain name format; 4. Customize pseudo-static URL: parse /article/123/title to /article.php?id=123; 5. Prevent image link theft: Check the Referer header, return the prompt image or 403 if it is not from this site; 6. Multi-condition combination redirection: match malicious crawlers through HTTP_USER_AGENT and jump to blocked page; 7. Simple URL redirection: Jump the old page 301 to the new page to maintain SEO weight; 8. Turn on beautiful URL: point all non-file and non-directory requests to index.php to support front-end controller mode; all rules need to take effect after RewriteEngine On is turned on. It is recommended to test and backup configuration items one by one to prevent errors from causing unavailability of the service.
Apache RewriteRule is a powerful feature provided by Apache's mod_rewrite module for rewriting URL requests. It is often used to implement SEO-friendly links, website jumps, prevent link theft, and forced HTTPS jumps. Here are several common and practical RewriteRule examples for .htaccess
files or Apache virtual host configurations.

1. Force HTTPS jump
Redirect all HTTP requests to HTTPS:
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
-
RewriteCond %{HTTPS} off
: determines whether it is currently non-HTTPS. -
R=301
: Return to 301 Permanent redirect. -
L
: It means that this is the last rule and will not be processed in the future.
Suitable for scenarios where HTTPS is required for the entire site.
2. Remove file extensions (such as .html or .php)
Hide the .php
extension, such as accessing /about
actually loading /about.php
:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9_-] )$ $1.php [L]
-
!-f
and!-d
: Make sure that the requested file or directory is not a real existing one, and avoid conflicts. -
^([a-zA-Z0-9_-] )$
: Match URLs without extensions. -
$1.php
: Internal rewrite to the.php
file of the same name.
.php
can be replaced with.html
, which works for static pages.
3. Forced to bring www or not domain names
Forced www:
RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
Forced to not bring www (more common):
RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
-
[NC]
: Ignore case. - Using 301 jumps is beneficial to SEO to unify domain name weights.
4. Customize pseudo-static URL (such as the article ID is displayed as the title)
Rewrite /article/123/my-great-article
to /article.php?id=123
:
RewriteEngine On RewriteRule ^article/([0-9] )/([a-zA-Z0-9_-] )$ /article.php?id=$1 [L]
- The first bracket captures the article ID.
- The second bracket captures the title (for SEO only, negligible).
- The actual processing still uses
id
parameter.
This method makes the URL more friendly while the backend logic remains unchanged.
5. Prevent image link thieves
Block other websites from directly referring to your image resources:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain\.com/.*$ [NC] RewriteRule \.(jpg|jpeg|png|gif|webp)$ https://yourdomain.com/nohotlinking.jpg [R,L]
- Check if
Referer
header is empty (allows direct access) or comes from your domain name. - Match common image formats and return prompt image when link stolen.
Can be replaced with a return 403 status code:
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
6. Multi-condition combination: Redirect only to specific user agents
For example: Block some crawlers or redirect mobile users:
RewriteEngine On RewriteCond %{HTTP_USER_AGENT} ^BadBot [NC,OR] RewriteCond %{HTTP_USER_AGENT} SpamBot [NC] RewriteRule ^.*$ https://example.com/blocked.html [R,L]
-
OR
represents the "or" relationship, and the next condition is triggered only if it is met. - Used to block malicious crawlers or test robots.
7. Simple URL redirection (old page → new page)
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]
- Suitable for keeping old links available after the website is redesigned.
- Use
R=301
to tell the search engine that it has been migrated permanently.
8. Enable "Pretty URLs" support (such as commonly used in PHP frameworks)
For example, frameworks such as Laravel, Symfony, etc. need to point all requests to index.php
:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,L]
-
QSA
: Keep the original query parameters (such as?id=1
). - Suitable for Front Controller mode.
Tips
- Turn on RewriteEngine : All rules must have
RewriteEngine On
. - Test order : The rules are executed in order, and note that
L
flag is used to avoid subsequent interference. - Debugging tips : You can use
RewriteLog
(old version) or pass the 404 logcurl -I
test to jump. - Scope : The path in
.htaccess
does not have leading/
, and may need to be adjusted in the virtual host.
Basically these common scenarios. It is recommended to test one by one when actually using it to avoid accidental damage to normal requests. RewriteRule is powerful, but a regular error may cause the entire website to be inaccessible. It is best to back up the configuration before modification.
The above is the detailed content of Apache rewrite rule examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

When encountering a "ConnectionRefused" error, the most direct meaning is that the target host or service you are trying to connect to explicitly reject your request. 1. Check whether the target service is running, log in to the target machine to check the service status using systemctlstatus or psaux, and start manually if it is not started; 2. Confirm whether the port is listening correctly, use netstat or ss command to check whether the service is listening to the correct port, modify the configuration file if necessary and restart the service; 3. Firewall and security group settings may cause connection denied, check the local firewall rules and cloud platform security group configuration, and temporarily close the firewall during testing; 4. IP address or DNS resolution errors may also cause problems, use ping or

Enabling KeepAlive can significantly improve website performance, especially for pages that load multiple resources. It reduces connection overhead and speeds up page loading by keeping the browser and server connection open. If the site uses a large number of small files, has duplicate visitors, or attaches importance to performance optimization, KeepAlive should be enabled. When configuring, you need to pay attention to setting a reasonable timeout time and number of requests, and test and verify its effect. Different servers such as Apache, Nginx, etc. all have corresponding configuration methods, and you need to pay attention to compatibility issues in HTTP/2 environments.

ToenableOCSPstaplinginApache,ensureyoumeettheprerequisitesandconfigurethenecessarydirectives.First,confirmyouareusingApache2.4.1ornewerwithmod_sslenabled,OpenSSL0.9.8hornewer,andhaveavalidSSLcertificateinstalled.Next,edityourApacheSSLvirtualhostconfi

The mod_proxy_wstunnel module is the key to Apache's handling of WebSocket connections, which ensures that requests are correctly forwarded to the backend and the connection is constantly opened. 1. First enable the mod_proxy and mod_proxy_wstunnel modules, and restart the Apache service; 2. Use the ws:// or wss:// protocol when configuring VirtualHost to ensure path matching; 3. Add the RequestHeader to set Upgrade and Connection headers to support protocol switching; 4. Configure valid certificates and point to the wss:// address when using SSL/TLS; 5. Test through browser console, wscat and other tools

To improve Apache performance, optimize configuration parameters are required. 1. Adjust KeepAlive parameters: Enable MaxKeepAliveRequests and set to 500 or higher, and set KeepAliveTimeout to 2~3 seconds to reduce connection overhead. 2. Configure the MPM module: Set StartServers, MinSpareServers, MaxSpareServers and MaxClients in prefork mode; set ThreadsPerChild and MaxRequestWorkers in event or worker mode to avoid excessive load. 3. Control memory usage: based on the memory usage of a single process

Apache's default web root directory is /var/www/html in most Linux distributions. This is because the Apache server provides files from a specific document root directory. If the configuration is not customized, systems such as Ubuntu, CentOS, and Fedora use /var/www/html, while macOS (using Homebrew) is usually /usr/local/var/www, and Windows (XAMPP) is C:\xampp\htdocs; to confirm the current path, you can check the Apache configuration file such as httpd.conf or apache2.conf, or create a P with phpinfo()

To improve Apache security, we need to start from module management, permission control, SSL encryption, log monitoring, etc. 1. Close unnecessary modules such as mod_imap, mod_info, etc., and make use of the LoadModule line and restart the service to take effect; 2. Set the root directory permissions to 755 or below, restrict write permissions, and disable directory traversal and script execution in the configuration; 3. Enable HTTPS, use Let'sEncrypt certificate and disable the old version of the protocol and weak encryption suite; 4. Check the access and error logs regularly, combine fail2ban to block abnormal IP, and use IP restrictions on sensitive paths.

Enable HSTS to force browsers to access websites through HTTPS, improving security. 1. To enable HTTPS in Apache, you must first configure HTTPS, and then add Strict-Transport-Security response header in the site configuration file or .htaccess; 2. To configure max-age (such as 31536000 seconds), includeSubDomains and preload parameters; 3. Make sure that the mod_headers module is enabled, otherwise run sudoa2enmodheaders and restart Apache; 4. You can optionally submit to the HSTSPreload list, but it must satisfy that both the main site and the subdomain support HTTPS.
