Example for Ubuntu 16.04 and Ubuntu 18.04
Backends that return hard (301) or temporary (302 or newer 303) redirects to the browser – the browser executes them – can easily take the user away from your Nginx. This can be intercepted with Lua.
What I show here is at least legally in the grey area, but rather black (regarding Google). Do not bring into production! All the security headers that Google attaches to the requests will spoil your fun anyway.
Installation
# sudo apt purge nginx-* # maybe necessary, backup your /etc/nginx/… configs before!
sudo add-apt-repository ppa:nginx/stable
sudo apt-cache show nginx-extras | grep -P '((xenial)|(bionic))'
sudo apt install nginx-extras # Lua support (nginx-extras is > nginx-full)
Config
/etc/nginx/sites-available/test.conf
server
{
listen 80;
listen [::]:80;
server_name niegit.com;
# Nginx vs. Lua
#
# Comment: # vs. --
# Concat: NIL vs. ..
# $request_uri vs. ngx.var.request_uri # path with query string
# $is_args$args vs. ngx.var.is_args .. ngx.var.args # query string
# $1 vs. ngx.var[1] # regex capturing group 1
# $2 vs. ngx.var[2] # regex capturing group 2
location /
{
rewrite_by_lua_block
{
-- Probs with AJAX/XHR and/or Websockets!
ngx.log(ngx.ALERT, 'See this text in /var/log/nginx/error.log')
local map = {
GET = ngx.HTTP_GET,
POST = ngx.HTTP_POST,
}
ngx.req.read_body()
local res = ngx.location.capture('/location_2' .. (ngx.var.request_uri or ''), {
method = map[ngx.var.request_method],
body = ngx.var.request_body
})
-- Detect/change redirect...
local redirect_target = res.header.Location
if redirect_target and res.status > 300 and res.status < 309 then
ngx.log(ngx.ALERT, redirect_target)
local redirect_target_changed, n, err = ngx.re.gsub(redirect_target, 'https?[:]//(?:www[.])?google[.]com(?:[:][0-9]*)?', 'http://niegit.com')
ngx.log(ngx.ALERT, redirect_target_changed)
return ngx.redirect(redirect_target_changed, 303)
else
ngx.exec('@named_location_3')
return ngx.exit(ngx.HTTP_OK)
end
}
}
location /location_2
{
proxy_pass https://www.google.com/;
}
location @named_location_3
{
proxy_pass https://www.google.com$request_uri;
}
}
Activate
cd /etc/nginx/sites-enabled
sudo ln -s ../sites-available/test.conf test.conf
sudo nginx -t
sudo service nginx reload # or newer: sudo systemctl reload nginx
If there are no sites-available
and sites-enabled
folders, simply put test.conf
in your conf.d
folder.
Testing
curl -I niegit.com # not active at the moment
If you offer foreign backends under your own domain, this should only happen for test purposes or you ask the owner. The example shown here can of course be used legally for your own backends and save your ass. ;)