Skip to content

Instantly share code, notes, and snippets.

@iPublicis
Last active January 16, 2024 08:04
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save iPublicis/c5e8ae1fe3f516723c2a902830603afa to your computer and use it in GitHub Desktop.
Save iPublicis/c5e8ae1fe3f516723c2a902830603afa to your computer and use it in GitHub Desktop.
NODE.JS app in Apache - force www. and https: sample .htaccess - partialy based on vielhuber/.htaccess
#########################
#
# NODE.JS app running in Apache
# sample .htaccess - partialy based on vielhuber/.htaccess
# Also rules to enforce www. prefix and https: SSL access
#
# This file must be on the dir where Apache expects to find the website
# The Node App can be anywhere else but must be accessible as explained below.
#
# ModRewrite must be active on Apache
RewriteEngine On
# First check if domain starts with www. and add it
# then if not using SSL force it
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]
# Redirect all trafic to NODE.JS server.
# It must be running and, in this case, listening to port 60000
RewriteRule ^$ http://127.0.0.1:60000/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:60000/$1 [P,L]
@wellrafi
Copy link

thanks

@corinthian13
Copy link

corinthian13 commented Sep 14, 2022

A lot of confusion on this config, especially in shared hosting situations.

  1. Why do you need to FORCE all requests to be HTTPS ?

The Node.js application itself can explicitly code all legitimate requests to be HTTPS and WWW.
Any requests not fitting into the HTTPS and WWW schema can therefore be logged as potential hacks.

  1. You redirect ALL requests to the Node.js HTTP port on the server.

This creates a problem for requests for HTML/CSS/FEJS/IMGS/etc files.
In reality, you should only redirect requests with a defined pseudo-folder, e.g. "mynodeapp", to the Node.js port.

For example, the request to URL
https://www.mysite.com/mynodeapp/fetch-it

would be redirected to
http://127.0.0.1:60000/fetch-it

which is the server's Node.js app server.

But any request for a website page, e.g. the site's home page on URL

                                           https://www.mysite.com

would be directed straight to the website's root directory and the index.html file listed in the URL.

But this code doesn't perform the redirect successfully for me anyway using cPanel on shared hsoting.
I get a 503 error and "Service unavailable" message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment