Decline all URIs with tilde character in Nginx

Abstract: Block URIs containing a tilde character in Nginx to prevent security risks and reduce backend load.

Created: 2026-10-19 by

To block all URIs containing a tilde character in Nginx, use the regular expression location directive location ~ /~ combined with a return statement. This configuration matches any request path that includes a tilde anywhere after the domain name and immediately returns a 403 Forbidden or 404 Not Found status code, effectively rejecting the request before it reaches your application server.

Understanding the Tilde Character Risk

The tilde character (~) is historically associated with user home directories in Unix-like systems. While modern web applications rarely use this convention for public URLs, its presence in a URI often indicates a security misconfiguration, an automated attack, or a leftover from legacy file system structures. Attackers frequently probe for these characters to access sensitive files, attempt directory traversal, or exploit vulnerabilities in older software stacks that interpret tildes as special path delimiters. By explicitly declining these requests at the reverse proxy level, you reduce the load on your backend application servers. This simple filter prevents unnecessary processing of malformed or malicious traffic, enhancing both the performance and security posture of your Nginx deployment. It is a proactive measure that aligns with the principle of least privilege by denying access to resources that should never be publicly accessible via standard HTTP methods. For more insights on managing URL patterns in Nginx, see Creating List of URLs from Nginx Location Directive.

Configuring the Regex Location Block

Nginx processes location blocks in a specific order: exact matches first, then prefix matches, and finally regular expressions. To ensure that your tilde-blocking rule takes precedence over other generic rules, you must place it strategically within your server block. The most effective approach uses a regular expression location directive that matches the tilde character anywhere in the URI path. Open your Nginx configuration file, typically located at /etc/nginx/sites-available/default or within the /etc/nginx/conf.d/ directory. Inside the relevant server block, add a new location directive. The syntax requires the ~ modifier to indicate a case-sensitive regular expression match. The pattern itself should target the tilde character. A common misconception is that the regex must start with a slash, but since Nginx strips the leading slash from the URI before matching against location patterns, you can simply target the character directly or include the preceding slash depending on your specific needs. However, to catch /~file and /path/~to/file, the regex ~ /~ works because the URI passed to the regex context usually retains the leading slash in some contexts or the pattern is interpreted relative to the path. Actually, Nginx's regex locations match against the full URI including the leading slash. Therefore, the pattern ~ /~ will match any URI that contains a tilde preceded by a slash. If you want to be absolutely certain to catch any tilde, you might consider ~ .*~.*, but ~ /~ is sufficient for standard web paths where the tilde appears after the root. Here is the correct configuration snippet:
server {
    listen 80;
    server_name example.com;

    # Block any URI containing a tilde
    location ~ /~ {
        return 403 "Forbidden";
    }

    # Your other location blocks here
    location / {
        proxy_pass http://backend;
    }
}
This block instructs Nginx to evaluate the incoming URI against the regular expression. If the pattern matches, Nginx immediately executes the return directive, sending a 403 Forbidden response to the client. The request does not proceed to any further location matching or upstream proxying.

Case Sensitivity Considerations

By default, the ~ modifier performs a case-sensitive match. Since the tilde character is a single ASCII symbol, case sensitivity is generally not a concern for this specific character. However, if you were blocking other alphabetic characters, you would need to use ~* for case-insensitive matching. For the tilde, ~ is perfectly adequate and slightly more efficient. If you are dealing with internationalized domain names or complex encoding issues, ensure that your Nginx version supports UTF-8 properly. Modern versions of Nginx handle Unicode correctly, so a tilde encoded in UTF-8 will still be matched by the ASCII-based regex pattern.

Testing and Validating the Configuration

Before applying the changes to your production environment, always test the configuration syntax. Run the following command in your terminal:
sudo nginx -t
If the output indicates that the test is successful, reload Nginx to apply the new rules without dropping existing connections:
sudo systemctl reload nginx
To verify that the rule is working, use curl to send a test request to a URI containing a tilde. For example:
curl -I http://example.com/~test
You should receive a 403 Forbidden status code in the response headers. Additionally, test a normal URI like http://example.com/about to ensure that legitimate traffic is not being blocked. This validation step confirms that your regex is precise and does not have unintended side effects on other parts of your site. For more information on rewriting arguments and handling complex URL structures, refer to How to use NGINX rewrite of arguments: A Comprehensive Guide.

Optimizing Performance and Security

Blocking these requests at the Nginx level is significantly more efficient than handling them in your application code. Nginx operates at the connection layer, allowing it to reject invalid requests before they consume CPU cycles or memory on your backend servers. This is particularly important for high-traffic sites that may be subjected to automated scanning tools looking for vulnerable paths. Furthermore, returning a 403 Forbidden provides clear feedback to clients that the resource is unavailable due to policy restrictions, rather than a generic 404 which might encourage further probing. From a security perspective, this reduces the attack surface by hiding the existence of potential legacy paths or misconfigurations that could otherwise be exploited.

Frequently Asked Questions

What happens if I use a 404 instead of 403?

A 404 Not Found hides the fact that the path exists but is forbidden, which can sometimes deter attackers who are looking for specific error responses. However, a 403 Forbidden is more accurate for policy violations and clearly signals that the request was rejected by the server's configuration rather than the resource being missing.

Does this regex block tildes in query strings?

No, the location directive matches only the URI path, not the query string parameters. If you need to block tildes in query strings, you would need to use a separate if directive checking the $query_string variable, though this is less common and can impact performance.

Can I use this method to block other special characters?

Yes, you can modify the regex pattern to match other characters such as backslashes or null bytes. For example, location ~ /\\ would block URIs containing a backslash. Always ensure your regex is anchored correctly to avoid false positives.

Why is my config not taking effect after editing?

Ensure you have run nginx -t to validate the syntax and then reloaded the service with systemctl reload nginx. Simply restarting the service with restart can cause brief downtime, while reload applies changes gracefully. Also check that the block is inside the correct server context.

Should I block tildes in subdomains too?

The configuration applies to the entire server block, affecting all hostnames served by that virtual host. If you have different requirements for different subdomains, you should create separate server blocks for each and apply the tilde-blocking rule only where necessary.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More