Skip to content

Commit

Permalink
feat: basic support in nginx for supporting redirects
Browse files Browse the repository at this point in the history
We can generate a list of redirects in `config/nginx-redirects.conf` during
build and nginx will use this to perform server-side redirects for us
  • Loading branch information
kennethkalmer authored and Jimmy MacGregor committed Dec 5, 2022
1 parent e2bc77a commit 42a44f7
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ public
!.env.example
graphql-types.ts
cli
dist
dist
config/nginx-redirects.conf
1 change: 1 addition & 0 deletions config/.tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodejs 16.18.1
16 changes: 16 additions & 0 deletions config/nginx-redirects.conf.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# This is an example of how the nginx redirects should look like.
#
# When building the site, part of the output should be this file,
# populated with the data from the redirect metadata from the pages
#
# Nginx has a limit on how big the redirects-map.conf can be, which is controlled
# via map_hash_bucket_size variable. If you get the following error:
#
# [emerg]: could not build the map_hash,
#
# you should increase the map_hash_bucket_size to account for the filesize. Say your
# nginx-redirects.conf is 30Kb, you set the map_hash_bucket_size variable in the http
# block of nginx.conf to 30720;

# Redirect from /old_page to /new_page
/old_page /new_page;
21 changes: 18 additions & 3 deletions config/nginx.conf.erb
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ http {

log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met;
error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>;

error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %> error;

include mime.types;
default_type application/octet-stream;
Expand All @@ -32,6 +31,17 @@ http {
# Must read the body in 5 seconds.
client_body_timeout <%= ENV['NGINX_CLIENT_BODY_TIMEOUT'] || 5 %>;

map_hash_max_size 8192;
map_hash_bucket_size 8192;

# Creates a map of redirects for us
map $uri $redirected_url {
default "none";
<% if File.exists?(File.dirname(__FILE__) + '/nginx-redirects.conf') %>
include nginx-redirects.conf;
<% end %>
}

server {
listen <%= ENV["PORT"] %> reuseport;
server_name _;
Expand All @@ -48,6 +58,11 @@ http {
return 301 https://$host$request_uri;
}

root /app/output; # path to your app
# Apply our redirects
if ($redirected_url != "none") {
rewrite ^ $redirected_url permanent;
}

root /app/public; # path to your app
}
}

0 comments on commit 42a44f7

Please sign in to comment.