Geoff
Geoff

Reputation: 6649

Apache htaccess configuration for nodejs apps fails

I have created a .htaccess file with the following

RewriteEngine On

RewriteBase /

 RewriteRule http://127.0.0.1:3034/ [P,L]
 RewriteCond %{REQUEST_FILENAME} !-f    
 RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/(.*)$ http://127.0.0.1:3034/$1 [P,L]

I have a nodejs app running at 127.0.0.1:3034 but whenever i visit the site with the htaccess already it doesnt load the nodejs app. I have placed the .htaccess on the domain root folder.

I cannot edit the vhost files so the .htaccess file seems to be a better option when running nodejs apps in apache2 What am i missing out in my configiration

I have checked on This question

Upvotes: 0

Views: 93

Answers (1)

arkascha
arkascha

Reputation: 42935

There are two issues with your attempt:

  1. the first RewriteRule does not make any sense
  2. A RewriteRule operates on relative paths when implemented in dynamic configuration files (".htaccess"), as opposed to absolute paths when implemented in the real http server's host configuration. Which is why the leading slash in your second RewriteRule prevented that rule from ever getting applied.

This is a slightly modified version of your approach:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)$ http://127.0.0.1:3034/$1 [P]

For this to work you obviously need both the rewriting and the proxy module to be loaded and activated in the apache http server.

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Upvotes: 2

Related Questions