Templating.
Depending on the type of page you want to serve: home, section, article, etc... the server knows how to respond to different page requests.
If the header code and footer code repeats over multiple pages you include this partials in those different templates
Since your question is focused on websites havig N pages say for example a website with many products, the design for a product looks the same, so all you need is to instruct the server how to handle a specific route:
example.com
head
welcome
footer
example.com/products
head
allProducts (pagination etc)
footer
example.com/products/101
head
product<id>
footer
here the server detects that a request for a route has some ID after /products/, your backend logic should use the article (product template), go grab that product ID from the database (image, images, title, description, content, price etc) and populate such single template with that data - and send it to the client.
That way no matter how many products (pages) you have, you need only one HTML template.
SPA (Single Page App) follows the same principle, just updating the content with AJAX (no page refresh)