Nginx does not have directory-level configuration file like Apache’s .htaccess file which is required for CompressX to work. All configuration on a Nginx server has to be done at the server level by an administrator.
In this tutoiral, we are going to show you how to configure Nginx for CompressX to work.
Step 1: Connect to Your Server
Establish an SSH connection to your website. You can do that using an SSH client like PuTTY.
Step 2: Locate the Configuration File
Find and open the configuration file used by your domain using command below:
/etc/nginx/sites-available/example.com
Remeber to replace example.com with your own domain.
Step 3: Add Rewrite Rules for CompressX
On the configuration file that opens, add the following rules and ensure these rules are placed within the server { ... }
block and before other location { ... }
directives and any include
directives within the server { ... }
block.:
# BEGIN CompressX
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;
add_header Cache-Control "private";
expires 365d;
try_files
/wp-content/compressx-nextgen/$path.$ext$ext_avif
/wp-content/compressx-nextgen/$path.$ext$ext_webp
$uri = 404;
}
# END CompressX
Step 4: Check and Remove Existing Image Rules
On some Nginx server, the configuration file might already have similar rules for image formats. You can check for a location
directive that includes extensions like .css
, .js
, and image formats.
Example of Existing Rules:
location ~* ^.+\.(css|js|jpg|jpeg|png|gif|webp|ico|eot|otf|woff|woff2|ttf)$ {
expires max;
...
}
If you find similar rules, remove the following extensions from the location
directive:
-
jpg
andjpeg
(orjpe?g
)png
gif
webp
Step 5: Add Required MIME Types
Check if WebP and AVIF MIME types are supported on the server.
To do that, edit the confirguration file using command:
/etc/nginx/mime.types
and add the following lines within the types { ... }
block if they are missing:
image/webp webp;
image/avif avif;
This ensures Nginx recognizes these image formats.
Step 6: Restart Nginx
Run this command to restart the Nginx server to take all changes effect:
systemctl restart nginx
Done. CompressX should now be able to function properly on your Nginx server.
If you have any issues or questions, please feel free to contact us.