One place for hosting & domains

      Browser

      How To Inspect A Website In Any Browser [Chrome, Safari, Firefox]

      Think of the internet as a giant iceberg. The average user only sees the tip of the surface: the website interfaces shown on our screens, but every webpage rests on massive foundations of code.

      Lines and lines of HTML, CSS, and JavaScript synthesize to construct the experiences we mindlessly scroll and tap through daily.

      What if you could peek behind the curtain?

      The ability to inspect website code lives directly inside your browser. Today’s popular browsers like Chrome, Firefox, and Safari contain built-in developer tools with the Inspect Element feature that helps you play around with the front-end technologies of any web page.

      This guide will teach you how to access and use the Inspect Element feature in all three browsers. We’ll also discuss what we can achieve using these browsers’ developer tools and how Inspect Element helps.

      Let’s dive right in!

      What Is Inspect Element?

      Inspect Element is a utility, usually found within your browser’s developer tools, that lets you view and manipulate the code — HTML, CSS, and JavaScript — that constructs any webpage.

      When you open Inspect Element, it shows you various code segments that build the website.

      You can highlight page sections to reveal the corresponding source code. Alternatively, clicking on a line of the original source code will highlight its matching visual element on the rendered page. This linking of front-end code and design lets you understand how websites are built.

      Inspect Element is a utility, usually found within your browser’s developer tools, that lets you view and manipulate the code — HTML, CSS, and JavaScript — that constructs any webpage.

      Nerd Note: Inspect Element allows digital marketers to see how specific changes will affect the appearance of a web page without making any changes to the live site. This can help test new CTA buttons, drop-down menus, color schemes, and other design elements. You can even see if your website is responsive on different devices.

      You can tweak text content, colors, fonts, layouts, animations, and more, to preview changes. The webpage remains unaltered externally, and refreshing returns your local view to the original state.

      Who Is It For?

      While Inspect Element is primarily considered a web developer tool, its practical uses span beyond coding. Here’s how various roles can benefit:

      • Developers: Debug layout issues, test code edit, and improve site performance.
      • Designers: Visualize new style ideas and preview designs across devices.
      • Marketers: Check SEO data, export icons/images, and modify text locally.
      • Writers: Anonymize screenshots and locally edit articles.
      • Support: Identify problems for documentation.
      • Students: Learn the implementation of web technologies.

      Essentially, anyone involved with websites whether it’s building, designing, running, writing about, or just using them, can discover new perspectives through inspection.

      Let’s look at exactly why you should start inspecting elements on the web.

      Why Inspect Websites?

      Let’s explore the key functions of the Inspect Element feature to understand how websites are constructed.

      1. Debug And Fix Problems

      Finding and fixing bugs is a massive use case for inspection tools. Developers can dive into the code to troubleshoot when a website appears broken to determine if it’s an issue with styling, layout, responsiveness, etc.

      Elements causing errors on the page are visually displayed in the inspector, allowing developers to narrow down the issue code quickly.

      DreamHost webpage with h1 highlighted and the corresponding code highlighted on the right in the inspect tool

      Since values can be tweaked live to non-destructively test fixes, it becomes easy to find the fix.

      Inspection tools also provide access to the Console panel. This allows for more advanced debugging and running custom JavaScript to see how the page reacts.

      So when tackling front-end and back-end website bugs, Inspect Element gives the power to unravel where problems originate.

      2. Understand Web Development

      For new developers still learning HTML, CSS, or JavaScript, inspector tools greatly assist the learning process. Inspect Element lets you see professional implementations of what you’re trying to achieve on your website. Ultimately, helping improve your implementation.

      You can also test how changing elements and content in HTML impacts the page.

      the same DreamHost page pointing towards the h1 and the page code called "font-weight"

      For example, adjusting margin values to observe spacing shifts or targeted nested elements using CSS descendant selectors. The real-world context also sticks better than reading through textbook examples.

      Plus, seeing how expert web developers structure and optimize sites provides a blueprint for coding your pages. The ability to experiment coupled with viewable source code from popular sites facilitates rapid growth.

      3. Test Designs and Content

      Web designers frequently use inspector tools to mock up style changes quickly. Testing variations — like new fonts, resized elements, color palettes, etc. — can be done instantly without affecting production code.

      the same DreamHost webpage with the h1 highlighted and the inspect code showing "font-family" changed to times new roman reflected in the h1

      For example, compare typefaces to determine ideal readability or change the button colors to see what they look like. With Inspect Element tools, you can do that right within your browser instead of making the changes in an external device like Photoshop or Figma.

      Similarly, for writers and marketers, modifying text locally helps preview content and layout adjustments. From testing paragraph widths to inspecting metadata, easy editing without needing access to Content Management System (CMS) backends is valuable.

      DreamHost Glossary

      Content Management System (CMS)

      A Content Management System (CMS) is a software or application that provides a user-friendly interface for you to design, create, manage, and publish content.

      Read More

      4. View SEO Data

      Browser developer tools provide vital insights when considering a web page’s SEO and social meta. Examining meta tags — descriptions, titles, open graph tags — most crucially influences how links appear in SERPs and when shared.

      long inspect element field pointing out "meta data" fields, one for DreamHost and one for twitter with og:titles

      For example, most social networks read the og:title og:description. All this information is in a website’s <head> elements.

      5. Check Performance

      Inspect Element tools also cater to web performance audits for improving overall site speed and loading behavior. In Chrome, the Network tab will give you a load timeline, which includes how long each element took.

      the same DreamHost web page showing the performance audits within Inspect Element on Chrome

      When inspecting pages, you can view total download times and resource requests and break this data into individual elements. Find out which images, fonts, or JavaScript files drag down performance. Then, address the issues directly: compress assets, implement caches, and defer nonessential scripts.

      Network inspection also allows throttling to mimic slow connections on mobile or poor wifi. Discover usability flaws by measuring loading times across simulated connections. Are pages still functional on 3G? Do some files block rendering? This information can help you improve your overall website page speed.

      6. And More

      This just scratches the surface of what’s possible through Inspect Element. We’ve mainly focused on use cases for developers, but designers, writers, and marketers can accomplish many goals discussed prior without coding expertise. You’ll also find analyzing accessibility and security vulnerabilities often leverages inspection capabilities.

      Now that you hopefully better understand all you can achieve by inspecting web pages, let’s quickly look at how these tools work before jumping into practical walkthroughs.

      How Browser Developer Tools Work

      The core of all major browser Inspect Element interfaces revolves around the Document Object Model (DOM).

      When a web page loads, the browser processes markup (HTML), presentation (CSS), and logic (JavaScript) to construct a DOM instance.

      The DOM essentially represents the page structure as a tree of parent-child node elements. Developers can instantly interact with this live representation using inspector tools to read, edit, and visualize corresponding changes.

      So when you toggle CSS declarations on and off while inspecting, rewrite conditional logic, or hide specific HTML nodes, for example, the matching DOM nodes update in real-time. This is how alterations display live without actually changing any source files externally.

      Behind the scenes, browsers apply changes made through inspection tools by temporarily overriding the default CSS and HTML. These modifications only exist for your browser and revert to normal once you refresh the page (or just close the tab and come back later).

      Inspecting Elements In Google Chrome

      As one of the world’s most popular browsers today, Google Chrome, accounting for over 70% of the browser market share, is equipped for nearly any inspection needed out of the box.

      Pressing Ctrl+Shift+I (Windows) or Command+Option+I (Mac) instantly launches Chrome’s DevTools interface to analyze any available webpage or web app. You can also inspect specific elements on the page.

      same DreamHost web page showing the inspect element pages in dark mode

      Let’s break down how to access Chrome’s Inspector, navigate page elements efficiently, and test joint manipulations – from editing text to simulating mobile devices, touchscreen devices, and more. You can use the phone icon on the top-left corner of the console window.

      1. Open Developer Tools

      Start by navigating Chrome (or any Chromium-based browser) to any webpage you want to inspect. Right-click anywhere on the page and select Inspect from the context menu.

      Alternatively, use the above keyboard shortcut.

      DevTools appears docked at the bottom of your browser window on larger screens as default. You can open it as a separate window or change docking locations, too — click on the three vertical dots in the upper-right corner of the Inspect Element window.

      Wherever it renders, the first thing you’ll see is the main elements panel which shows all the HTML code.

      inspect element window devtools view in html starting with <html class> into the <head>

      Various other analysis tabs can be accessed across the top: Console, Sources, Network, etc.

      Depending on where the Inspect element window opens, one portion will show the page source code starting with <html>. As you click on different things in the code, the right (or lower) side shows the styles, including fonts, colors, margins, paddings, etc.

      This linking between code and appearance facilitates understanding and experimenting with changes. But before manipulating anything, let’s see how to target elements for inspection efficiently.

      2. Find Elements To Inspect

      As pages grow long and complex, scanning visually for the element you want and locating its code in dev tools can become tedious. Instead, use the node selection tool.

      In Chrome DevTools, click the icon on the top-left corner (of the inspector window) that resembles the selector crossed with the cursor (or press Ctrl/Cmd+Shift+C).

      same dreamhost page with company logo highlighted and the corresponding code highlighted in the inspect element box

      Your mouse now toggles element selection mode. Hover over any visual entity on the page and notice how the inspector code automatically highlights its DOM node.

      Now, clicking any element on the page will directly highlight the code that makes the element appear on the page. You can also see the styles right or below the HTML code. You can also use the search box or search tab to find elements. Alternatively, Ctrl+F (Windows) and Cmd+F (Mac) work too!

      Let’s see what we can edit with the elements selected.

      3. Interact With The DOM

      The inspect element feature also provides a way of interacting with the Document Object Model (DOM) — the structured representation of page elements visible in the editor.

      Developers can leverage the DOM to reshape content, style, and interactivity directly within Chrome DevTools.

      Some common ways to manipulate elements include:

      • Editing text by making content fields directly editable.
      • Toggling CSS styles like colors and fonts to visually test styling changes in the CSS panel.
      • Modifying component attributes like links and buttons to reshape functionality.
      • Rearranging structural elements to prototype alternative layouts.

      The DOM updates live with changes made in the inspector view. So any tweaks preview instantly in the browser, then reset upon refresh, making experiments low risk during development.

      4. Test Responsiveness

      Beyond editing individual elements, inspector tools also provide environments to test responsiveness across a variety of devices and viewports.

      Chrome DevTools includes device mode simulation. You can select presets to emulate standard phone or tablet resolutions and touch capabilities. Or use the more advanced options to manually configure exact dimensions, pixel ratios, CPU throttling, and other metrics.

      This allows rapid validation of aspects like:

      • Layouts at various breakpoints.
      • Touch target spacing for mobile users.
      • Site performance on low-powered devices.
      • Accessibility on different hardware.

      The ability to preview pages on simulated mobile screens during development helps perfect responsiveness and progressive enhancement delivery. Testing across a wide spectrum of emulated devices ensures broad browser and device support.

      Inspecting Elements In Firefox

      Firefox provides its webpage inspection tools rivaling the functionality of Chrome DevTools. Access Firefox Inspector using the same Inspect Element shortcuts as Chrome: Ctrl+Shift+I (Windows) and Cmd+Opt+I (Mac).

      You can also use the keyboard shortcut Ctrl+Shift+C (Windows) and Cmd+Opt+C (Mac) to open the inspect element panel, allowing you to click on an element on the page to jump to the code directly.

      same dreamhost page showing the inspect element box in firefox

      1. View DOM Attributes

      When analyzing complex interfaces, focus states and dynamic effects rely on HTML attributes instead of CSS. Right-click any element within Inspector views and choose Show DOM Properties.

      right-click menu from inspector box highlighting the "Show DOM Properties" option

      This displays all native attributes associated with the node. You can directly edit values here to modify component behavior through the Inspector rather than requiring code changes.

      For example, adjusting the range slider min/max and step increments visually sets bounds, changing the checkbox/radio button names groups toggles, overwriting dataset properties hooks different remote data, and the list goes on and on.

      2. Work Visually With Box Model Diagrams

      Firefox eases inspection by showing the padding, borders, and margins right as you move your cursor around the website.

      same dreamhost webpage showing different elements (image, h1) within and overlapping grids

      When clicking any node, the Inspector panel cycles between three states: geometry off, box model overlay only, and both overlay plus markup outlines.

      This can be useful when you want to test if your spacing, padding, and margins have been appropriately applied to the elements.

      It also makes it more straightforward to fix any issues since you can click through specific elements and see precisely what CSS styling is affecting them. Geometric analysis here can help beginners grasp spatial relationships faster.

      3. Edit Colors With A Color Picker

      Within Inspector, click any color swatch next to any property accepting colors like background, border, etc. It’ll show you a color slider, alpha setting, and a color picker to pull colors from your open page.

      Within Inspector, click any color swatch next to any property accepting colors like background, border, etc. It’ll show you a color slider, alpha setting, and a color picker to pull colors from your open page.

      You no longer need to spend time guessing color codes or checking your design assets for the code being used. Pick it from existing elements or even images on the page.

      Inspecting Elements in Safari

      Safari offers the Webkit Inspector for inspecting pages on macOS systems primarily. However, you need to enable the development menu before accessing it.

      Open Safari and click Safari from the Menu > Settings > Advanced. Check the box for “Show features for web developers.

      show features for web developers shown at the bottom page of the advanced options

      Now you can visit any website and right-click to see the “Inspect element” option available,

      right-click menu showing the "Inspect Element" option

      You can also use the keyboard shortcut, Cmd+Opt+C, to access the Inspect Element feature.

      Timelines And Network Speed

      Similar to most other browsers, Safari offers powerful timelines within the Safari Inspector. The resources list helps you instantly identify which files are causing rendering delays and what the reason could be. You can also see what scripts are blocking the page load.

      3D View Of Website Layers

      right-click menu showing the "Inspect Element" option

      If you want to analyze the layers that make up the website, simply go to the Layers tab and you’ll be presented with a full 3D model of all the layers

      Ways To Use Inspect Element

      Now that we’ve set up inspector tools let’s discuss some practical ways they can be used. Here are just a few common usage examples:

      Change Text Or Images

      One helpful capability is modifying textual content or image assets directly within the editor. You can tweak headlines, swap logos, anonymize details, and more.

      To edit any text or images, inspect the element you want to change first, then double-click within its bounds in the code editor to make the content editable.

      Input anything you want, and press enter to make the changes live (temporarily).

      Change Colors, Fonts, And Styling

      When inspecting various elements like links, buttons, menus, or galleries — you’ll notice attributes that define associated behavior like href destination URLs, carousel view box data sources, and more.

      Much like editing textual content and CSS properties and style sheets, these HTML-level traits can be manipulated directly within Inspector.

      The DOM updates these changes on the spot. So you can immediately see how the changes reshape component functionality without coding:

      • Modify the href of links and buttons to redirect clicks elsewhere temporarily.
      • Adjust tab role and aria tags to test accessibility improvements.
      • Swap thumbnail image src attributes while building galleries.

      Change Element State

      Beyond basic styling, Inspector tools also allow modifying interactive element states like hover, focus, and active. Right-click elements and use the Force state options (Google Chrome) to visualize how components appear during usage.

      right click menu opened over inspect element with "Force state" option highlighted

      For example, toggle a button’s active state to ensure the pushed effect is visible to users. Check disabled field borders to see if they offer proper contrast. Validate menu links highlight appropriately on focus during keyboard navigation testing.

      Hide Or Delete Items

      Finally, bulk hiding or deletion of page elements is possible, too. It can help identify unnecessary code bloating page size, block elements from rendering correctly, or unexpectedly hide desired content from users.

      close up of dreamhost webpage with inspect element highlighting a <p class> code

      To try this, simply highlight any element in the code and press delete to remove it from the rendered view instantly.

      In the screenshot, we have deleted the DreamHost’s homepage heading from our view. You can do much more with Inspect Element as you explore it.

      FAQs

      Can you use Inspect Element on any website?

      Yes, Inspect Element works universally across all modern websites. However, some websites render code on the server side and only push JavaScript objects to the front end. This is generally done to prevent web scrapers from pulling data, and it can become difficult for you to understand the site structure using Inspect Element.

      Do changes made in Inspect Element save permanently?

      No. Any edits made via inspector tools only temporarily render locally within your browser view. Refreshing reverts to the default external page content. Changes will not impact actual source files whatsoever.

      Can other users see tweaks when inspecting websites?

      Inspect Element edits cannot be viewed by other users browsing websites, even while signing into the same browser profile across multiple devices. Think of changes as exclusive to your machine only.

      Are there other developer tools beyond Inspect Element?

      Absolutely. As mentioned earlier, Console, Sources, Network, and other analysis tabs also prove invaluable during development. Plus, browser extensions extend DevTools capabilities even further.

      Don’t Just View Websites, Interact With The Code

      Playing around with the Inspect Element feature peels back the curtain on how websites work. Letting you peek at the HTML, CSS, and JavaScript underneath any page you click can easily help you understand why something looks and feels the way it does.

      So, as you surf around, keep that Inspect Element tool handy. Let curiosity guide you as you click around to see what makes things appear as they do. Who knows, you might just pick up new methods to help the web become an even more accessible and fun place!

      How To Implement Browser Caching with Nginx’s header Module on CentOS 8


      Not using CentOS 8?


      Choose a different version or distribution.

      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The faster a website loads, the more likely a visitor is to stay. When websites are full of images and interactive content run by scripts loaded in the background, opening a website is not a simple task. It consists of requesting many different files from the server one by one. Minimizing the quantity of these requests is one way to speed up your website.

      One method for improving website performance is browser caching. Browser caching tells the browser that it can reuse local versions of downloaded files instead of requesting the server for them again and again. To do this, you must introduce new HTTP response headers that tell the browser how to behave.

      Nginx’s header module can help you accomplish browser caching. You can use this module to add any arbitrary headers to the response, but its major role is to properly set caching headers. In this tutorial, we will use Nginx’s header module to implement browser caching.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Creating Test Files

      In this step, we will create several test files in the default Nginx directory. We’ll use these files later to check Nginx’s default behavior and then to test that browser caching is working.

      To infer what kind of file is served over the network, Nginx does not analyze the file contents; that would be prohibitively slow. Instead, it looks up the file extension to determine the file’s MIME type, which denotes its purpose.

      Because of this behavior, the content of our test files is irrelevant. By naming the files appropriately, we can trick Nginx into thinking that, for example, one entirely empty file is an image and another is a stylesheet.

      Create a file named test.html in the default Nginx directory using truncate. This extension denotes that it’s an HTML page:

      • sudo truncate -s 1k /usr/share/nginx/html/test.html

      Let’s create a few more test files in the same manner: one jpg image file, one css stylesheet, and one js JavaScript file:

      • sudo truncate -s 1k /usr/share/nginx/html/test.jpg
      • sudo truncate -s 1k /usr/share/nginx/html/test.css
      • sudo truncate -s 1k /usr/share/nginx/html/test.js

      The next step is to check how Nginx behaves with respect to sending caching control headers on a fresh installation with the files we have just created.

      Step 2 — Checking the Default Behavior

      By default, all files will have the same default caching behavior. To explore this, we’ll use the HTML file we created in step 1, but you can run these tests with any example files.

      So, let’s check if test.html is served with any information regarding how long the browser should cache the response. The following command requests a file from our local Nginx server and shows the response headers:

      • curl -I http://localhost/test.html

      You should see several HTTP response headers:

      Output: Nginx response headers

      HTTP/1.1 200 OK Server: nginx/1.14.1 Date: Thu, 04 Feb 2021 18:23:09 GMT Content-Type: text/html Content-Length: 1024 Last-Modified: Thu, 04 Feb 2021 18:22:39 GMT Connection: keep-alive ETag: "601c3b6f-400" Accept-Ranges: bytes

      In the second to last line you will find the ETag header, which contains a unique identifier for this particular revision of the requested file. If you execute the previous curl command repeatedly, you will find the exact same ETag value.

      When using a web browser, the ETag value is stored and sent back to the server with the If-None-Match request header when the browser wants to request the same file again — for example, when refreshing the page.

      We can simulate this on the command line with the following command. Make sure you change the ETag value in this command to match the ETag value in your previous output:

      • curl -I -H 'If-None-Match: "601c3b6f-400"' http://localhost/test.html

      The response will now be different:

      Output: Nginx response headers

      HTTP/1.1 304 Not Modified Server: nginx/1.14.1 Date: Thu, 04 Feb 2021 18:24:05 GMT Last-Modified: Thu, 04 Feb 2021 18:22:39 GMT Connection: keep-alive ETag: "601c3b6f-400"

      This time, Nginx will respond with 304 Not Modified. It won’t send the file over the network again; instead, it will tell the browser that it can reuse the file it already has downloaded locally.

      This is useful because it reduces network traffic, but it’s not good enough to achieve good caching performance. The problem with ETag is that the browser always sends a request to the server asking if it can reuse its cached file. Even though the server responds with a 304 instead of sending the file again, it still takes time to make the request and receive the response.

      In the next step, we will use the headers module to append caching control information. This will make the browser to cache some files locally without explicitly asking the server if its fine to do so.

      Step 3 — Configuring Cache-Control and Expires Headers

      In addition to the ETag file validation header, there are two caching control response headers: Cache-Control and Expires. Cache-Control is the newer version, with more options than Expires and is generally more useful if you want finer control over your caching behavior.

      If these headers are set, they can tell the browser that the requested file can be kept locally for a certain amount of time (including forever) without requesting it again. If the headers are not set, browsers will always request the file from the server, expecting either 200 OK or 304 Not Modified responses.

      We can use the header module to set these HTTP headers. The header module is a core Nginx module, which means it doesn’t need to be installed separately to be used.

      To add the header module, open the default server block Nginx configuration file in vi (here’s a short introduction to vi) or your favorite text editor:

      • sudo vi /etc/nginx/nginx.conf

      Find the server configuration block:

      /etc/nginx/nginx.conf

      . . .
      server {
          listen 80 default_server;
          listen [::]:80 default_server;
          server_name  _;
          root         /usr/share/nginx/html;
      . . .
      

      Add the following two new sections here: one before the server block, to define how long to cache different file types, and one inside it, to set the caching headers appropriately:

      Modified /etc/nginx/nginx.conf

      . . .
      # Expires map
      map $sent_http_content_type $expires {
          default                    off;
          text/html                  epoch;
          text/css                   max;
          application/javascript     max;
          ~image/                    max;
          ~font/                     max;
      }
      
      server {
          listen 80 default_server;
          listen [::]:80 default_server;
          server_name  _;
          root         /usr/share/nginx/html;
      
          expires $expires;
      . . .
      

      The section before the server block is a new map block that defines the mapping between the file type and how long that kind of file should be cached.

      We’re using several different settings in this map:

      • The default value is set to off, which will not add any caching control headers. It’s a safe bet for the content, we have no particular requirements on how the cache should work.

      • For text/html, we set the value to epoch. This is a special value that results explicitly in no caching, which forces the browser to always ask if the website itself is up to date.

      • For text/css and application/javascript, which are stylesheets and JavaScript files, we set the value to max. This means the browser will cache these files for as long as possible, reducing the number of requests considerably given that there are typically many of these files.

      • The last two settings are for ~image/ and ~font/, which are regular expressions that will match all file types containing image/ or font/ in their MIME type name (like image/jpg, image/png or font/woff2). Like stylesheets, both pictures and web fonts on websites can be safely cached to speed up page-loading times, so we set this to max as well.

      Note: These are just a few examples of the most common MIME types used on websites. You can get acquainted with the more extensive list of such types on Common MIME types site and add others to the map that you might find useful in your case.

      Inside the server block, the expires directive (a part of the headers module) sets the caching control headers. It uses the value from the $expires variable set in the map. This way, the resulting headers will be different depending on the file type.

      Save and close the file to exit.

      To enable the new configuration, restart Nginx:

      • sudo systemctl restart nginx

      Next, let’s make sure our new configuration works.

      Step 4 — Testing Browser Caching

      Execute the same request as before for the test HTML file:

      • curl -I http://localhost/test.html

      This time the response will be different. You will see two additional HTTP response headers:

      Nginx response headers

      HTTP/1.1 200 OK
      Server: nginx/1.14.1
      Date: Thu, 04 Feb 2021 18:28:19 GMT
      Content-Type: text/html
      Content-Length: 1024
      Last-Modified: Thu, 04 Feb 2021 18:22:39 GMT
      Connection: keep-alive
      ETag: "601c3b6f-400"
      Expires: Thu, 01 Jan 1970 00:00:01 GMT
      Cache-Control: no-cache
      Accept-Ranges: bytes
      

      The Expires header shows a date in the past and Cache-Control is set with no-cache, which tells the browser to always ask the server if there is a newer version of the file (using the ETag header, like before).

      You’ll find a difference in response with the test image file.

      • curl -I http://localhost/test.jpg

      Note the new output:

      Nginx response headers

      HTTP/1.1 200 OK
      Server: nginx/1.14.1
      Date: Thu, 04 Feb 2021 18:29:05 GMT
      Content-Type: image/jpeg
      Content-Length: 1024
      Last-Modified: Thu, 04 Feb 2021 18:22:42 GMT
      Connection: keep-alive
      ETag: "601c3b72-400"
      Expires: Thu, 31 Dec 2037 23:55:55 GMT
      Cache-Control: max-age=315360000
      Accept-Ranges: bytes
      

      In this case, Expires shows the date in the distant future, and Cache-Control contains max-age information, which tells the browser how long it can cache the file in seconds. This tells the browser to cache the downloaded image for as long as it can, so any subsequent appearances of this image will use local cache and not send a request to the server at all.

      The result should be similar for both test.js and test.css, as both JavaScript and stylesheet files are set with caching headers too.

      This means the cache control headers have been configured properly and your website will benefit from the performance gain and less server requests due to browser caching. You should customize the caching settings based on your website’s content, but the defaults in this article are a reasonable place to start.

      Conclusion

      The headers module can be used to add any arbitrary headers to the response, but properly setting caching control headers is one of its most useful applications. It increases performance for the website users, especially on networks with higher latency, like mobile carrier networks. It can also lead to better results on search engines that factor speed tests into their results. Setting browser caching headers is a crucial recommendation from Google’s PageSpeed and similar performance testing tools.

      You can find more detailed information about the headers module in Nginx’s official headers module documentation.



      Source link

      How To Implement Browser Caching with Nginx’s header Module on Ubuntu 20.04


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The faster a website loads, the more likely a visitor is to stay. When websites are full of images and interactive content run by scripts loaded in the background, opening a website is not a simple task. It consists of requesting many different files from the server one by one. Minimizing the quantity of these requests is one way to speed up your website.

      One method for improving website performance is browser caching. Browser caching tells the browser that it can reuse local versions of downloaded files instead of requesting the server for them again and again. To do this, you must introduce new HTTP response headers that tell the browser how to behave.

      Nginx’s header module can help you accomplish browser caching. You can use this module to add any arbitrary headers to the response, but its major role is to properly set caching headers. In this tutorial, we will use Nginx’s header module to implement browser caching.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Creating Test Files

      In this step, we will create several test files in the default Nginx directory. We’ll use these files later to check Nginx’s default behavior and then to test that browser caching is working.

      To infer what kind of file is served over the network, Nginx does not analyze the file contents; that would be prohibitively slow. Instead, it looks up the file extension to determine the file’s MIME type, which denotes its purpose.

      Because of this behavior, the content of our test files is irrelevant. By naming the files appropriately, we can trick Nginx into thinking that, for example, one entirely empty file is an image and another is a stylesheet.

      Create a file named test.html in the default Nginx directory using truncate. This extension denotes that it’s an HTML page:

      • sudo truncate -s 1k /var/www/html/test.html

      Let’s create a few more test files in the same manner: one jpg image file, one css stylesheet, and one js JavaScript file:

      • sudo truncate -s 1k /var/www/html/test.jpg
      • sudo truncate -s 1k /var/www/html/test.css
      • sudo truncate -s 1k /var/www/html/test.js

      The next step is to check how Nginx behaves with respect to sending caching control headers on a fresh installation with the files we have just created.

      Step 2 — Checking the Default Behavior

      By default, all files will have the same default caching behavior. To explore this, we’ll use the HTML file we created in step 1, but you can run these tests with any example files.

      So, let’s check if test.html is served with any information regarding how long the browser should cache the response. The following command requests a file from our local Nginx server and shows the response headers:

      • curl -I http://localhost/test.html

      You will see several HTTP response headers:

      Output: Nginx response headers

      HTTP/1.1 200 OK Server: nginx/1.18.0 (Ubuntu) Date: Tue, 02 Feb 2021 19:03:21 GMT Content-Type: text/html Content-Length: 1024 Last-Modified: Tue, 02 Feb 2021 19:02:58 GMT Connection: keep-alive ETag: "6019a1e2-400" Accept-Ranges: bytes

      In the second to last line you will find the ETag header, which contains a unique identifier for this particular revision of the requested file. If you execute the previous curl command repeatedly, you will find the exact same ETag value.

      When using a web browser, the ETag value is stored and sent back to the server with the If-None-Match request header when the browser wants to request the same file again — for example, when refreshing the page.

      We can simulate this on the command line with the following command. Make sure you change the ETag value in this command to match the ETag value in your previous output:

      • curl -I -H 'If-None-Match: "6019a1e2-400"' http://localhost/test.html

      The response will now be different:

      Output: Nginx response headers

      HTTP/1.1 304 Not Modified Server: nginx/1.18.0 (Ubuntu) Date: Tue, 02 Feb 2021 19:04:09 GMT Last-Modified: Tue, 02 Feb 2021 19:02:58 GMT Connection: keep-alive ETag: "6019a1e2-400"

      This time, Nginx will respond with 304 Not Modified. It won’t send the file over the network again; instead, it will tell the browser that it can reuse the file it already has downloaded locally.

      This is useful because it reduces network traffic, but it’s not good enough to achieve good caching performance. The problem with ETag is that browsers always send a request to the server asking if it can reuse its cached file. Even though the server responds with a 304 instead of sending the file again, it still takes time to make the request and receive the response.

      In the next step, we will use the headers module to append caching control information. This will make the browser cache some files locally without explicitly asking the server if its fine to do so.

      Step 3 — Configuring Cache-Control and Expires Headers

      In addition to the ETag file validation header, there are two caching control response headers: Cache-Control and Expires. Cache-Control is the newer version, with more options than Expires and is generally more useful if you want finer control over your caching behavior.

      If these headers are set, they can tell the browser that the requested file can be kept locally for a certain amount of time (including forever) without requesting it again. If the headers are not set, browsers will always request the file from the server, expecting either 200 OK or 304 Not Modified responses.

      We can use the header module to set these HTTP headers. The header module is a core Nginx module, which means it doesn’t need to be installed separately to be used.

      To add the header module, open the default Nginx configuration file in nano or your favorite text editor:

      • sudo nano /etc/nginx/sites-available/default

      Find the server configuration block:

      /etc/nginx/sites-available/default

      . . .
      # Default server configuration
      #
      
      server {
          listen 80 default_server;
          listen [::]:80 default_server;
      
      . . .
      

      Add the following two new sections here: one before the server block, to define how long to cache different file types, and one inside it, to set the caching headers appropriately:

      Modified /etc/nginx/sites-available/default

      . . .
      # Default server configuration
      #
      
      # Expires map
      map $sent_http_content_type $expires {
          default                    off;
          text/html                  epoch;
          text/css                   max;
          application/javascript     max;
          ~image/                    max;
          ~font/                     max;
      }
      
      server {
          listen 80 default_server;
          listen [::]:80 default_server;
      
          expires $expires;
      . . .
      

      The section before the server block is a new map block that defines the mapping between the file type and how long that kind of file should be cached.

      We’re using several different settings in this map:

      • The default value is set to off, which will not add any caching control headers. It’s a safe bet for the content, we have no particular requirements on how the cache should work.

      • For text/html, we set the value to epoch. This is a special value that results explicitly in no caching, which forces the browser to always ask if the website itself is up to date.

      • For text/css and application/javascript, which are stylesheets and JavaScript files, we set the value to max. This means the browser will cache these files for as long as possible, reducing the number of requests considerably given that there are typically many of these files.

      • The last two settings are for ~image/ and ~font/, which are regular expressions that will match all file types containing image/ or font/ in their MIME type name (like image/jpg, image/png or font/woff2). Like stylesheets, both pictures and web fonts on websites can be safely cached to speed up page-loading times, so we set this to max as well.

      Note: These are just a few examples of the most common MIME types used on websites. You can get acquainted with the more extensive list of such types on Common MIME types site and add others to the map that you might find useful in your case.

      Inside the server block, the expires directive (a part of the headers module) sets the caching control headers. It uses the value from the $expires variable set in the map. This way, the resulting headers will be different depending on the file type.

      Save and close the file to exit.

      To enable the new configuration, restart Nginx:

      • sudo systemctl restart nginx

      Next, let’s make sure our new configuration works.

      Step 4 — Testing Browser Caching

      Execute the same request as before for the test HTML file:

      • curl -I http://localhost/test.html

      This time the response will be different. You will see two additional HTTP response headers:

      Output

      HTTP/1.1 200 OK Server: nginx/1.18.0 (Ubuntu) Date: Tue, 02 Feb 2021 19:10:13 GMT Content-Type: text/html Content-Length: 1024 Last-Modified: Tue, 02 Feb 2021 19:02:58 GMT Connection: keep-alive ETag: "6019a1e2-400" Expires: Thu, 01 Jan 1970 00:00:01 GMT Cache-Control: no-cache Accept-Ranges: bytes

      The Expires header shows a date in the past and Cache-Control is set with no-cache, which tells the browser to always ask the server if there is a newer version of the file (using the ETag header, like before).

      You’ll find a difference in response with the test image file:

      • curl -I http://localhost/test.jpg

      Note the new output:

      Output

      HTTP/1.1 200 OK Server: nginx/1.18.0 (Ubuntu) Date: Tue, 02 Feb 2021 19:10:42 GMT Content-Type: image/jpeg Content-Length: 1024 Last-Modified: Tue, 02 Feb 2021 19:03:02 GMT Connection: keep-alive ETag: "6019a1e6-400" Expires: Thu, 31 Dec 2037 23:55:55 GMT Cache-Control: max-age=315360000 Accept-Ranges: bytes

      In this case, Expires shows the date in the distant future, and Cache-Control contains max-age information, which tells the browser how long it can cache the file in seconds. This tells the browser to cache the downloaded image for as long as it can, so any subsequent appearances of this image will use local cache and not send a request to the server at all.

      The result should be similar for both test.js and test.css, as both JavaScript and stylesheet files are set with caching headers too.

      This means the cache control headers have been configured properly and your website will benefit from the performance gain and less server requests due to browser caching. You should customize the caching settings based on your website’s content, but the defaults in this article are a reasonable place to start.

      Conclusion

      The headers module can be used to add any arbitrary headers to the response, but properly setting caching control headers is one of its most useful applications. It increases performance for the website users, especially on networks with higher latency, like mobile carrier networks. It can also lead to better results on search engines that factor speed tests into their results. Setting browser caching headers is a crucial recommendation from Google’s PageSpeed and similar performance testing tools.

      More detailed information about the headers module can be found in Nginx’s official headers module documentation.



      Source link