Redirect Domain on Laravel Forge using NGINX while preserving Let's Encrypt Certificate
This article has been published a while ago.
If this is a technical article some information might be out of date. If something is terribly broken, let me know and I will update the article accordingly.
Recently I needed to redirect the traffic for an entire domain, that is hosted on Laravel Forge, to another domain while preserving the SSL certificate from Let's Encrypt.
The paths should be mapped 1:1. So http://example.com/path/to/site
would be redirected to http://new-example.com/path/to/site
.
To ensure that certbot
on Laravel Forge can still issue a valid SSL certificate for the now deprecated example.com
domain, I needed to make sure that requests to /.well-known/acme-challenge/
are not redirected.
After tinkering with various ideas I landed on the following solution.
location / {
# Check if request is used to generate Let's Encrypt SSL Certificate
if ($request_uri !~ ^/.well-known/acme-challenge/) {
# Redirect to the new domain including query parameters
return 301 https://example.com$request_uri;
}
# Create alias to /home/forge/.letsencrypt directory.
# Taken from /etc/nginx/forge-conf/example.com/server/letsencrypt_challenge.conf
auth_basic off;
allow all;
alias /home/forge/.letsencrypt;
}
Replace example.com
with the domain you would like to redirect to and then replace the existing location / { try_files index.php }
block with the snippet above in your Laravel Forge NGINX configuration.