Home
About
Resume
Projects
Links
Blog
Back to Contents
# Apache2 Rewrite URL #### Installation Install Apache2 web server if it is not installed ``` sudo apt install apache2 -y ``` Activate rewrite module ``` sudo a2enmod rewrite ``` #### Usage General usage ``` RewriteEngine on RewriteRule [match_uri] [rewrite_uri] [flags] ``` match_uri, rewrite_uri can be matched with regex ```txt RewriteRule ^match\.html$ rewrite.html [NC,L] # Behavior: # input URL: http://domain.com/match.html # return as: http://domain.com/rewrite.html ``` #### Examples ##### **#1** Hide index.* from URL 1\. Open `/etc/apache2/apache2.conf`: ```bash sudo nano /etc/apache2/apache2.conf ``` 2\. Add `RewriteRule`, e.g. for `/var/www/html`: ```txt
Options Indexes FollowSymLinks RewriteEngine on RewriteRule ^(.*)/index\.([a-zA-Z]+)$ /$1/ [R=301,L]
``` ##### **#2** using /1/2/3 instead of ?a=1&b=2&c=3 for URL parameters 1\. Open `/etc/apache2/apache2.conf`: ```bash sudo nano /etc/apache2/apache2.conf ``` 2\. Add `RewriteRule`, e.g. for `/var/www/html/blog`: ```txt
Options Indexes FollowSymLinks RewriteEngine on RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ ?t=$1&d=$2&f=$3
``` > - Below two URL behavior the same: > - https://lomanhei.com/blog/Software/2021-09-26/Apache2-Rewrite-URL > - https://lomanhei.com/blog/?t=Software&d=2021-09-26&f=Apache2-Rewrite-URL ##### **#3** Rewrite URL using .htaccess > In general, you should only use .htaccess files when you don't have access to the main server configuration file. 1\. Ensure the server configuration allows `.htaccess` files override certain directory, e.g. `/var/www/html`: ```txt
AllowOverride All
# Behavior: it allows override for "/var/www/html" and all of its sub directories ``` 2\. Add `.htaccess` to the target directory, e.g. /var/www/html/testing: ```txt RewriteEngine on RewriteRule ^(.*)$ /404.html [R=301,L] # Behavior: it redirects all access under /var/www/html/testing to /404.html ``` #### Source **Documentation link**: [Apache mod_rewrite](http://httpd.apache.org/docs/current/rewrite/) **Reference**: [When (not) to use .htaccess files](https://httpd.apache.org/docs/current/howto/htaccess.html#when) **Reference**: [Apache Rewrite with Htaccess 理解與技巧](https://medium.com/%E6%B5%A6%E5%B3%B6%E5%A4%AA%E9%83%8E%E7%9A%84%E6%B0%B4%E6%97%8F%E7%BC%B8/htaccess-with-rewrite-3dba066aff11)
Previous Post:
Fix WSL Docker Fail to Stop
Next Post:
Markdown Syntax
Loading