Welcome! Log In Create A New Profile

Advanced

Drop all (deny all) traffic requests not made by lan or home ip.

Posted by Danran 
Drop all (deny all) traffic requests not made by lan or home ip.
February 14, 2023 10:16AM
I am trying to block all traffic to a specific Nginx and wordpress page by using a "deny all;" entry in location directives. However, the pages that I am blocking don't block any traffic after adding the directive. The best solution I have found is to have Nginx redirect traffic to a missing page by including the "error_page 403 =444;" directive just below the "deny all;" directive. Instead of redirecting, I want the server to just either drop all traffic and not respond (preferred), or show an "access denied" page to requests made by any other than my lan IP and home IP. What must I do to get the above desired result?

Below is my nginx virtual hosts file:

server {
listen 80;
#listen [::]:80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}

server {
listen 443 ssl http2;
#listen [::]:443 ssl http2;
server_name example.com www.example.com;
root /var/www/example.com/;

##
# SECURITY HEADERS
##

# Add Strict Transport Security Response Header with "always Paramater", to help prevent MITM attacks.
# HSTS (ngx_http_headers_module is required) (63072000 seconds)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

# Add a content security policy header
#add_header Content-Security-Policy "frame-ancestors 'self';";
# https://gabriel.nu/tutorials/Ubuntu-20.04-NGINX-LEMP-secure-web-server-for-WordPress-DIY.html
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;

# Secure MIME Types with X-Content-Type-Options. Below line adds the X-Frame-Options header in Nginx.
add_header X-Content-Type-Options "nosniff" always;

# Referrer Policy
#add_header Referrer-Policy "strict-origin";
# https://gabriel.nu/tutorials/Ubuntu-20.04-NGINX-LEMP-secure-web-server-for-WordPress-DIY.html
add_header Referrer-Policy "no-referrer-when-downgrade" always;

add_header Permissions-Policy "geolocation=(), autoplay=(), enctypted-media=(), midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=(self)";

# This line adds the X-FastCGI-Cache header in HTTP response. It can be used to validate whether
# the request has been served from the FastCGI cache or not.
add_header X-FastCGI-Cache $upstream_cache_status;

# When we use a webpage, we can leave various pieces of data in the browser that we’d like to clear out if the user logs out or deletes their account.
# Clear Site Data gives us a reliable way to do that. Here is the RFC if you want more details Clear Site Data .
# I decided to enable it globally on all pages via:
add_header Clear-Site-Data "*";

# (Already included in module)
# Prevent click jacking by adding an X-Frame-Options header
add_header x-frame-options "SAMEORIGIN" always;

# (Already included in module)
# Enable X-XSS-Protection header in Nginx
add_header X-XSS-Protection "1; mode=block" always;

# User recommendation from linuxbabe.com for fastcgi to keep working (only use this if fcgi cache status is not getting hits)
#fastcgi_ignore_headers Cache-Control Expires Set-Cookie;

##
# SSL
##

# Path to signed certificate
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # Managed by admin
# Path to Intermediate certificates
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # Managed by admin
# Verify chain of trust of OCSP response using Root CA and Intermediate certs
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem; # Managed by admin
# Perfect Forward Secrecy Diffie-Hellman 4098 parameters
ssl_dhparam /etc/ssl/private/dhparams4096.pem; # Managed by admin

# Mozilla Modern Compatibilty SSL configuration with OCSP stapling turned on and strict settings for A+ SSL Security rating
ssl_protocols TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLERequires nginx >= 1.13.0 else use TLSv1.2 # Dropping TLSv1.1 for modern compatability.
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m; # about 40000 sessions
ssl_session_tickets off;

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 1.1.1.1 1.0.0.1;

##
# ERROR & ACCESS LOGS (adding "if=$log_ip" to access log lines will exclude your own ip address from access logs to prevent skewing data)
##

# Netdata Access Log
access_log /var/log/nginx/example.com.access.log netdata if=$log_ip;
# Amplify Access Log
access_log /var/log/nginx/example.com.access.log apm if=$log_ip;
# Error Log
error_log /var/log/nginx/example.com.error.log warn;

##
# PAGESPEED
##

# enable pagespeed module on this server block
pagespeed on;
pagespeed Domain http*://*.example.com;
# Include UNIVERSAL Settings for Pagespeed Module
include /etc/nginx/pagespeed.conf;

##
# LOCATIONS
##

index index.php index.html index.htm index.nginx-debian.html;

### BEGIN "WebP Converter for Media" Wordpress Plugin ###
set $ext_avif ".avif";
if ($http_accept !~* "image/avif") {
set $ext_avif "";
}

set $ext_webp ".webp";
if ($http_accept !~* "image/webp") {
set $ext_webp "";
}

location ~ /wp-content/(?<path>.+)\.(?<ext>jpe?g|png|gif|webp)$ {
add_header Vary Accept;
expires 365d;
try_files
/wp-content/uploads-webpc/$path.$ext$ext_avif
/wp-content/uploads-webpc/$path.$ext$ext_webp
$uri =404;
}
### END "WebP Converter for Media" Wordpress Plugin ###

# LINUXBABE
location / {
try_files $uri $uri/ /index.php;
}

location ~ /.well-known {
allow all;
}

location = /favicon.ico {
log_not_found off;
access_log off;
}

location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}

# LINUXBABE
location ~ ^/wp-json/ {
rewrite ^/wp-json/(.*?)$ /?rest_route=/$1 last;
}

# LINUXBABE
location ~* /wp-sitemap.*\.xml {
try_files $uri $uri/ /index.php$is_args$args;
}

# LINUXBABE
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

# LINUXBABE
location = /50x.html {
root /usr/share/nginx/html;
}

# DISALLOW ACCESS of /xmlrpc.php EXCEPT FROM internal IP's and Home & Apartment IP's.
location ~ /xmlrpc.php$ {
allow 192.168.1.0/24; # LAN IP Address
allow xxx.xx.xxx.xxx; # Home IP address
deny all;
error_page 403 =444;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

# DISALLOW ACCESS of /admin EXCEPT FROM internal IP's and Home & Apartment IP's.
location ^~ /admin/ {
allow 192.168.1.0/24; # LAN IP Address
allow xxx.xx.xxx.xxx; # Home IP address
deny all;
error_page 403 =444;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

# DISALLOW ACCESS of /wp-login.php EXCEPT FROM internal IP's and Home & Apartment IP's.
location ~ /wp-login.php {
allow 192.168.1.0/24; # LAN IP Address
allow xxx.xx.xxx.xxx; # Home IP address
deny all;
error_page 403 =444;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

# DISALLOW ACCESS of PHP In Upload Folder
location /wp-content/uploads/ {
location ~ \.php$ {
deny all;
}
}

# DISALLOW ACCESS of hidden files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}

# LINUXBABE
# DISALLOW ACCESS to hidden files
location ~ /\.ht {
access_log off;
log_not_found off;
deny all;
}

##
# FASTCGI CACHE / FASTCGI SKIP CACHE RULES
##

### START SKIP CACHE RULES ###

# LINUXBABE
# Prevent FastCGI caching for certain things/pages
set $skip_cache 0;

# LINUXBABE
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $skip_cache 1;
}
if ($query_string != "") {
set $skip_cache 1;
}

# LINUXBABE
# Don't cache uris containing the following segments
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/feed/*|index.php|/.*sitemap.*\.(xml|xsl)") {
set $skip_cache 1;
}

# LINUXBABE
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
set $skip_cache 1;
}

# SPINUPWP.COM https://spinupwp.com/hosting-wordpress-yourself-server-monitoring-caching/
# In most cases you shouldn’t cache the shopping cart, checkout, or account pages as they are generally unique for each customer.
# Additional cache exclusions can be added using conditionals and regular expressions (regex).
# The following example will work for the default pages (Cart, Checkout, and My Account) created by WooCommerce :
if ($request_uri ~* "/(cart|checkout|my-account)/*$") {
set $skip_cache 1;
}

# LINUXBABE
# Sometimes I want to test the upstream (PHP-FPM and MariaDB) response time, so I also add the following
# lines to tell Nginx to bypass the FastCGI cache for my own IP addresses, and then my LAN IP addresses.
# Note: This was not fullly understood from linuxbabe tutorial fastcgi chapter, and
# therefore was modified by admin. Use carefully.

# Skip the fastCGI Cache for ATNT Public IP, and the local network.
if ($remote_addr ~* "xxx.xx.xxx.xxx|192.168.0..*") {
set $skip_cache 1;
}

# IMPORTANT NOTE WITH SEO:
# If you use the Yoast SEO or Google XML Sitemap plugins to generate sitemap, then
# you also need to move the Yoast/Google XML rewrite rules below the skip cache rules.

### END SKIP CACHE RULES ###

# LINUXBABE
# Pass Fastcgi to php
location ~ \.php$ {
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include snippets/fastcgi-php.conf;
# FastCGI cache
fastcgi_cache oddcake.net;
fastcgi_cache_valid 200 301 302 7d;
fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
fastcgi_cache_min_uses 1;
fastcgi_cache_lock on;
# If you use Google XML sitemap, or Yoast SEO plugin to generate sitemap, then you also need to move the Yoast rewrite rules below the skip cache rules.
# If the value of $skip_cache is 1, then the first directive tells Nginx to send the request to
# the upstream PHP-FPM server, instead of trying to find files in the cache. Note: fastcgi_cache_bypass $skip_cache and
# fastcgi_no_cache $skip_cache should be uncommented if using google XML sitemap plugin, or Yoast SEO Plugin, or if you want to enable skip cache rules above.
# Tell Nginx to send request to upstream PHP-FPM server, instead of trying to find files in the cache.
# If the value of $skip_cache is 1, then the first directive tells Nginx to send request to upstream PHP-FPM server, instead of trying to find files in the cache.
fastcgi_cache_bypass $skip_cache;
# This directive tells Nginx not to cache the response.
fastcgi_no_cache $skip_cache;
# This line adds the X-FastCGI-Cache header in HTTP response. It can be used to validate whether
# the request has been served from the FastCGI cache or not. Linuxbabe had this directove on in "location ~ \.php$ {".
# However, we don't use it here because it intercepts the initial headers and removes them. Lets keep the initial headers with a comment.
add_header X-FastCGI-Cache $upstream_cache_status;
# User recommendation from linuxbabe for fastcgi to keep working. (only use this if fastcgi cache status is not getting hits).
#fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
}

###
# Nginx Cache Purging in Wordpress with Nginx Cache Purge Module
##

# This enables the ngx_http_cache_purge_module.so module to work with Nginx Helper in Wordpress.
# Cache Purging should be restricted to allowed IP addresses.
# If not set, an attacker may be able to wipe your nginx fastcgi cache using simple GET requests. # (Linuxbabe User Comment).
# This location block enables cache purge but restricts it to your ip address and to your loopback address.
location ~ /purge(/.*) {
allow 127.0.0.1; # Server Loopback Address
allow 149.28.125.6; # Server IPv4 address
deny all;
# Enable http-cache-purge module in nginx for above IP addresses
fastcgi_cache_purge oddcake.net "$scheme$request_method$host$1";
}

# LINUXBABE (Duplicate. Mostly. But added some files extensions)
# A long browser cache lifetime can speed up repeat visits to your page
location ~* \.(txt|flv|pdf|avi|mov|ppt|wmv|mp3|ogg|webm|aac|jpg|ogg|ogv|svgz|eot|otf|mp4|rss|atom|zip|tgz|gz|rar|bz2|doc|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|jpeg|gif|png|swf|jpeg|webp|svg|woff|woff2|ttf|css|js|ico|xml|otf|woff|woff2)$ {
access_log off;
log_not_found off;
expires 1y;
}
}

Dan Ran
dan@danran.rocks
https://danran.rocks
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 148
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready