Nginx: Redirecting URLs Without Trailing Slashes
Today, we're diving into a nifty little Nginx trick that's going to boost your SEO game. We're talking about redirecting URLs without trailing slashes.
As you know search engines like Google see URLs with and without trailing slashes as different pages. This can lead to duplicate content issues, which is a big no-no for SEO. By standardizing your URLs, you're telling search engines exactly which version of your pages they should index, giving your site an SEO boost. Let's Get to the Nginx config.
Here's how you can configure your Nginx server to redirect those pesky trailing slashes. Below is the configuration file youβll need to tweak.
server {
root /var/www/ggrealestate.barcelona/public;
index index.php index.html index.htm;
server_name ggrealestate.barcelona;
# Redirect URLs with trailing slashes to URLs without trailing slashes
location / {
if ($request_uri ~* ^(.+)/$) {
return 301 $1;
}
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
This is where the magic happens, but outside of Hogwarts. We're checking if the requested URL ends with a slash. If it does, we redirect it (301) to the same URL without the trailing slash.
if ($request_uri ~* ^(.+)/$) {
return 301 $1;
}
try_files $uri $uri/ /index.php?$query_string;
And there you have it! With just a few tweaks, you can ensure your URLs are clean, consistent, and SEO-friendly. Nginx. So next time youβre optimizing your site, remember this little trick.