How to Serve WebP Images on Nginx

How to Serve WebP Images on Nginx

by admin

After the images are optimized, they are served as webp on Apache servers automatically. However, this situation is not possible on nginx servers, so it is necessary to set it manually.

By default the config file is /etc/nginx/nginx.conf and thanks to the include /etc/nginx/conf.d/*.conf; line in this config file, all files in the /etc/nginx/conf.d folder are included.

You need to create a file called webp.conf in the /etc/nginx/conf.d/ directory and paste the code below.

map $http_accept $webp_suffix{
    default "";
    "~*webp" ".webp";
}

Finally, you need to find the config file of the site. Since the path of the config file may change depending on the control panel, we cannot say the config file path. After you find the config file, you can paste the code below inside of the server{} section.

If the browser caching rules exists in the config file, the webp rules must be added before the browser caching rule because the browser caching rule prevents the webp rules from working.

# WebP
location ~* ^/.+\.(png|gif|jpe?g)$ {
    # BEGIN Browser Caching of WebP
    expires 180d; 
    add_header Pragma "public";
    add_header Cache-Control "public";
    # END Browser Caching of WebP

    add_header Vary Accept;
    try_files $uri$webp_suffix $uri =404;
}

# Browser Caching
location ~* \.(css|js|ico|gif|jpeg|jpg|webp|png|svg|eot|otf|woff|woff2|ttf|ogg)$ {
    expires 180d; 
    add_header Pragma "public";
    add_header Cache-Control "public";
}

Related articles

Placeholder Image
Utf-8 Character Encoding Problem

HTML files are typically served as text/html. The character encoding (or ‘charset’) of this file is UTF-8. If the page…

How to Redirect All HTTP to HTTPS .htaccess
How to Redirect All HTTP to HTTPS .htaccess

If you have installed an SSL certificate on your website, the website may not be available via a secure HTTPS…

Placeholder Image
Buffer Callback Filter

You can use the Buffer Callback Filter feature to make any changes to the html source of a page or…

Ready to get started?

Purchase your first license and see why 1,500,000+ websites globally around the world trust us.