Redirect Apache Requests to Applications

When requests come into the Apache Web server, they are routed by default to the files in the Document Root. Sometimes we want to redirect those requests elsewhere. We can do this with the Rewrite module.

Add the Rewrite directives to the Apache config file, an .htaccess file, or do what I usually do and add it to the Virtual Host file.

Rewrite for SPAs

To direct requests to Single Page Web-apps, such as those that are build with React and Vue.js. This is what works for me.

<Directory "/var/www/my-app/dist">
Options Indexes FollowSymLinks
order allow,deny
allow from all

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]

PHP Applications

Often when using Apache to host a PHP Web application, it’s desirable to handle incoming requests with PHP. By default, Apache will try to handle requests. But, we can use the rewrite module to send requests to specified PHP scripts.

<Directory "/path/to/webroot">
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?/$1 [L]

Leave a Reply

Your email address will not be published. Required fields are marked *