I have an app hosted on AWS Elastic Beanstalk, which is assigned an environment URL as such:
<my-appname>.<aws-region>.elasticbeanstalk.com
I also have registered a domain name as such:
my-appname.com
In AWS Route 53, I have an A ALIAS
pointing my-appname.com
to the EB environment as such:
my-appname.com
> A ALIAS <my-appname>.<aws-region>.elasticbeanstalk.com
From my registrar, I have Route 53 nameservers set up to manage DNS via Amazon.
Everything Works Fine
What I’d like to understand how to do is ensure any requests to the <my-appname>.<aws-region>.elasticbeanstalk.com>
domain get 301
‘d to the my-appname.com
domain.
I’m using an Apache RewriteRule
currently to redirect all non-www requests to the www version of the website using this in a .config
file:
<If "'%{HTTP_HOST}' !~ /^www./">
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</If>
Would it be good practice to simply change the HTTP_HOST
to my-appname.com
?
EDIT: That approach doesn’t seem to work anyway. Not sure why?
2
Answers
My current understanding is the best approach for this is to use server-level re-writes to address the issue. An example (for an Apache server) is as follows:
When using Elastic Beanstalk (Amazon Linux 2) and Nginx you have two solutions:
Extend Elastic Beanstalk default nginx.conf
Create a file named
.platform/nginx/conf.d/redirections.conf
inside your source code that contains:Nginx documentation: https://www.nginx.com/blog/creating-nginx-rewrite-rules/
(example.com being your own domain)
Create your own nginx.conf that replaces the default one from Elastic Beanstalk
/etc/nginx/nginx.conf
by connecting to your Elastic Beanstalk EC2 instance using SSH (*).platform/nginx/nginx.conf
inside your source code and paste the contentYou should end up with a
/etc/nginx/nginx.conf
(taken from Amazon Linux 2 as of 2022/05/08) that looks like this:More on Nginx configuration
While at it, I also recommend other modifications to your Nginx configuration.
Redirect www to root
Example with redirecting http://www.example.com to example.com.
Prerequisites:
HTTP security headers
I recommend to set these HTTP headers for security:
File compression (.js, .css, .html…)
You can enable compression with
gzip on;
. Unfortunately you cannot extend the default nginx.conf to enable compression. You will have to copy-paste and modify the original nginx.conf (.platform/nginx/nginx.conf
).Note: you can have your own
.platform/nginx/nginx.conf
and still use files inside.platform/nginx/conf.d/
directory.Redirect HTTP to HTTPS
2 solutions: use the load balancer (Application Load Balancer) or a custom
.platform/nginx/nginx.conf
.(*) Open port 22 in your EC2 instance security group (something like
*AWSEBSecurityGroup*
) then go to:EC2 > Instances > Connect > EC2 Instance Connect (browser-based SSH connection)