Chris Moore

Rewrite the WordPress uploads url path in Nginx

Green box with arrows

When migrating an existing website from standard WordPress to the Roots Bedrock framework, a common task is ensuring that your links continue to work in with the new directory structure. Here is a quick RegEx you can add to your NGINX configuration file that will redirect any inbound traffic that is using the old URL to your new page:

rewrite ^/wp-content/(.*)$ /app/$1 permanent;

Here is a breakdown of the metacharacters used:

  • ^ Matches the starting position within the string. In this case it matches the URL of the website.
  • ()Defines a marked subexpression. The string matched within the parentheses can be recalled later as variable $1, $2, etc - based on the order of appearance.
  • . Matches any single character. We're taking the entirety of the URI after /wp-content/.
  • * Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc

 

And we use permanent at the end to indicate that this is redirect should use the '301 Moved Permanently' status code as opposed to the '302 Found' status code which would be returned if you use temporary.

For reference, here is an example of an NGINX server block using the rewrite configuration:

server {
listen 80;
listen [::]:80;
server_name example.com
root /var/www/example.com;
index index.php index.html index.htm;
rewrite ^/wp-content/(.*)$ /app/$1 permanent;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.3-fpm.sock;
}
}