Can we add http response headers directly into html pages - html

I need to add response headers like X-Frame, Cache-control, Pragma etc directly into the html code, may be, using attributes in html elements?
It is for help pages which are directly coming from a directory via href link.
Is there any way to add headers to these htmls?

You can use meta to replicate some of these. Normally not the ideal solution, but look into the http-equiv attribute of meta tags. I believe a lot of these have been deprecated in newer browsers.
Examples:
<meta http-equiv="Cache-control" content="no-cache"/>
<meta http-equiv="X-Frame-Options" content="sameorigin"/>
<meta http-equiv="pragma" content="no-cache"/>

In short: no, you cannot. HTML files are the body of an HTTP response; the headers must come from the server. Anything you could embed in the HTML file would just become part of the body.

You can add something like this, if php execution is enabled on your web server:
<?php
http_response_code(your_response_code)
?>
rest-of-your-html-code
This will execute a php script that will set the response code.

Related

HTML5 meta tags: if you remove a security meta tag, does the browser update accordingly?

If I have a CSP meta tag (as opposed to using an HTTP header), like so:
<meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'">
... and then I go into developer tools and remove that node, would the browser act as though it was never provided, or would the fact that it was added at all be persistent no matter what?
I'm asking because I want to know if I should use an HTTP header (which can't be modified), or if it's safe to just use this meta tag.
No. In the Content Security Policy spec it says:
Note: Modifications to the content attribute of a meta element after the element has been parsed will be ignored. [own markup]
I would read that as: "Once the meta tag's CSP is parsed, modifications to the tag (including deletions) will not effect the CSP".
But also note KayakinKoder's answer and make sure to place the meta tag at the very top of the head element:
Authors are strongly encouraged to place meta elements as early in the document as possible, because policies in meta elements are not applied to content which precedes them. In particular, note that resources fetched or prefetched using the Link HTTP response header field, and resources fetched or prefetched using link and script elements which precede a meta-delivered policy will not be blocked.
I definitely wouldn't put it in html. Even if you tell browsers to never cache thing X, some will eventually screw around and cache thing X "to be helpful". Lets say you want to change your CDN from example.net to differentcdn.com in the future; if any browsers have cached your CSP, your site will be broken. Or even worse, you accidentally edit the CSP CDN section to "exEmple.net" and deploy; browsers cache this, and your site is completely broken. We've had some users browsers cache 302 (temporary..) redirects that were clumsily put in an .htaccess file rather than completely server-controlled http.conf, what a nightmare; I don't trust browsers to do what they are supposed to do on anything extremely important that would break our app.
As far as I'm aware, headers are never cached.
Finally, I would recommend looking into Google's strict CSP 3: https://csp.withgoogle.com/docs/strict-csp.html
It looks like this Content-Security-Policy meta tag is "protected", i.e. the browser remembers its value even when it is removed via dev tools.
You can simply try it with this simple example:
index.html
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src self;">
Then open dev tools and type in:
fetch('http://example.com')
You will see something like:
VM345:1 Refused to connect to 'http://example.com/' because it violates the following Content Security Policy directive: "default-src self 'mocky.io'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
Let's try it with removing that particular meta tag
document.querySelector("[http-equiv='Content-Security-Policy']").remove()
fetch('http://example.com')
You will still see the same error.
I tried it in the most recent versions of chrome and firefox. Maybe some least known browsers or lower versions will react differently. Unfortunately, I couldn't find more info about it but I don't see any particular reason for not using it.

HTML <meta> tag

I am reading a Servlet "HellowWorld" tutorial. The servelet is defined in a HelloWorldServelet.java class. Super simple to output "Hell world" message to the client request. The only html file is "index.html" below. I don't understand how the meta tag works. As I run the application in the web server, it automatically this page with the URL:
http://localhost:8080/helloworld/HelloWorld
How the attributes "http-equiv" and "content" work together with the servelet?
<html>
<head>
<meta http-equiv="Refresh" content="0; URL=HelloWorld">
</head>
</html>
The Refresh meta-tag automatically redirects the browser to the URL given after the specified amount of time.
Without seeing the tutorial you are using, I can't imagine why you would need to use it for your task.
https://en.wikipedia.org/wiki/Meta_refresh
"http-equiv" and "content"
they are used for adding message headers in http response .
For example http-equiv can be used to refresh the page.
if you specify something like this
<meta http-equiv="refresh" content="45">
you are instructing browser to refresh in every 45 seconds.
Other than refresh,you can use it to set cookies and etc.

Why does Chrome not redirect using meta refresh

An application that I work with has a PL/SQL package that creates a page and uses a function to create META tags.
It creates a webpage with a META tag exactly like this :
<META HTTP-EQUIV="Refresh" NAME="Refresh" CONTENT="1; URL=PaymentSubmit.html">
The problem is that Chrome does not like the NAME="Refresh" attribute. It does not redirect the page, although it does redirect properly in IE and Firefox
If I remove the NAME attribute, so that it looks like this it works in all browsers :
<META HTTP-EQUIV="Refresh" CONTENT="1; URL=PaymentSubmit.html">
What's going on here? I can't find a W3C standard for META redirect, so does every browser make up it's own rules ? I'm not sure if it ever worked in Chrome, but since I never heard any bug reports I assume it used to work in Chrome.
Anyone have a similar problem ?
Thanks
If you check the w3c wiki you can find the following quote:
Exactly one of the name, http-equiv, and charset attributes must be specified.
It mean's it is not valid html that both - name and http-equiv attributes are set.
Read this W3C's HTML and XHTML Techniques test on meta refresh:
Find all meta elements in the document. For each meta element, check
if it contains the attribute http-equiv with value "refresh"
(case-insensitive) and the content attribute with a number greater
than 0 followed by ;'URL=anyURL' (where anyURL stands for the URI that
should replace the current page).
The behavouir of the other browsers is not wrong, but chrome is more strict.
More details about the correct behavouir - and the valid reference - are available at http://www.w3.org/TR/html5/document-metadata.html#attr-meta-http-equiv-refresh
As far as browser support:
The support for <meta> refresh is there even in IE6
The syntax to be used is:
Place inside <head> to refresh page after 5 seconds:
<meta http-equiv="refresh" content="5">
Redirect to http://example.com/ after 5 seconds:
<meta http-equiv="refresh" content="5; url=http://example.com/">
Redirect to http://example.com/ immediately:
<meta http-equiv="refresh" content="0; url=http://example.com/">
If you plan to support javascript disablers (Which I don't think you should do :)
Do this:<noscript><meta http-equiv="refresh" content="0; url=url here"></noscript>
It is not a part of HTTP standard.
However, there are alternatives:
For refreshing the page after 5 seconds, do the below:
<body onload="javascript:setTimeout(function(){ location.reload(); },5000);">
If you want to redirect after 5 seconds, then do the below:
<body onload="javascript:setTimeout(function(){ window.location = 'http://example.com';},5000);">
If you want to redirect immediately:
<body onload="javascript:window.location='http://example.com'">
But there isn't any alternative for javascript disablers (yippee!!)
Conclusion:
So, my suggestion, would be to use my javascript alternatives, because they are not going to be replaced.
But <meta> refresh tag may be discontinued in the coming years.
More reading : http://en.wikipedia.org/wiki/Meta_refresh
For the <META tags, Microsoft has published specific guidelines:
Page and site guidelines for SEO
Specifically, for the <meta http-equiv="refresh"> element, Microsoft states the following:
A page redirect should provide both a message with the new page location and sufficient time for users to read the message. A page redirect with a time-out period of less than five seconds may result in a lower search-engine ranking.
To redirect a page, consider using an HTTP redirect instead. An HTTP redirect is more likely to transfer the authority of the old page to the new page.
Personally, instead of a <meta refresh tag, I would recommend you use a 301 Redirect. In PHP you could do, for example, the following:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.yourdomain.com/newpage");
?>
This method is better than the <meta refresh because usually a 301 redirect includes the address to which the resource has been moved. Web browsers will typically follow 301 redirects to the new location automatically, without the need for user action.
According to some definitions of 301 Redirect, it would even preserve old positions:
A 301 redirect should be used whenever a website is moved to a new domain name (URL) so that search engines will quickly change their indeces and, in theory, preserve the search engine rankings that the site had at the previous domain.
All this is in line with the fact that many shady websites use <meta refresh to open unwanted websites (spam/ advertisements etc.). Hence I would conclude that the refresh meta tag should not be used.
For the other meta tags, please read the following: 18 meta tags every webpage should have.
Keep in mind that not all meta tags are of crucial importance; for example, Google says it does not use the keywords meta tag in web ranking.
But remember: it is Better to have, and not need, than to need, and not have.
Just don't use the <META refresh ;)

Difference meta and PHP header

What is the difference between these two and should I use both ? I want my website to be fully UTF-8.
In PHP:
<?php
header("Content-Type: text/html; charset=utf-8");
?>
And the meta tag in HTML:
<meta charset="utf-8">
The HTTP Content-Type header should always be set, it's the primary source for the browser to figure out what kind of document it's dealing with. Only if this header is missing will the browser try to find an HTML meta tag which gives it the same information as a fallback.
It makes sense to set both flags though, since you may save the HTML document to disk, in which case the HTTP header will be gone for anyone needing it later.
You can find the exact rules for how a browser determines the document's charset here: http://www.w3.org/TR/html5/syntax.html#determining-the-character-encoding
header("Content-Type: text/html; charset=utf-8");
is server side and depends upon the PHP script calling it before it will send the new page to the client.
<meta charset="utf-8">
The meta element has two uses: either to emulate the use of an HTTP response header, or to embed additional metadata within the HTML document. So the Meta Tag is the best way to have utf-8 on your site.

Load index.html every time from the server and NOT from cache

I have a webpage index.html hosted on a particular server. I have pointed example.com to example.com/index.html. So when I make changes in index.html and save it, and then try to open example.com, the changes are not reflected. Reason that the webpages are being cached.
Then I manually refresh the page and since it loads the fresh copies and not from cache, it works fine. But I cannot ask my client to do so, and they want everything to be perfect. So my question is that is there a trick or technique as to how I can make the file load every time from the server and not from cache?
P.S: I know the trick for CSS, JS and images files, i.e. appending ?v=1 but don't know how to do it for index.html.
Any help would be appreciated. Thanks!
by this:
<meta http-equiv="expires" content="0">
Setting the content to "0" tells the browsers to always load the page from the web server.
The meta tags didn't worked for me so. i set the headers from the java class that implements filter or controller. and it worked. here is the code
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0); // Proxies.
There are only two most reliable way available as of 2018
1) **<meta http-equiv="expires" content="0">** Use this meta tag but be careful because this tag destroy the all cache of the page as soon as a web page processed by browser.
2) Generate an unique ID at server for each page request and append this id at the end of the all file name inside the HTML document with ? before the unique id append on images, documents, css/js files, videos etc which need to be load from the server every time. For example if you have the HTML tag like <img src="images/profile223.jpg" alt="profile picture"> then on server side append the unique id at the end of the file name like this echo '<img src="images/profile223.jpg?'.$uniqueid.'"" alt="profile picture">'; . In this example i use php but you can generate the unique ID on any language. All big companies like Google, Facebook, Microsoft, Twitter etc. uses this technique because it is most effective way and does not effect the cache data you want to store on user browser like login session id. This technique is cross browser compatible and support older version of IE, Firefox, Chrome, Safari and Opera. You may append the unique id at the end of the url using the same technique
You can try this below method. It worked for me.
Please add the below lines of code in your .htaccess file.
<IfModule mod_headers.c>
<FilesMatch "\.(html|php)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</FilesMatch>
<FilesMatch "\.(ico|pdf|jpg|png|gif|js|css)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>
</IfModule>
If you use the above code, browser will not cache .html files.
Adding this meta tags to the header works for most of the browsers (in that case index.html will not be cached):
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
A bit late but it might help someone else!
You can send extra headers with the file to tell the client (the browser, that is) that the file must not be cached. If you got Apache, take a look at mod_expires. If you use a server side scripting language, like PHP, you can solve it using that too.
i ever meet this problem with my website. in your URL add the q=''
http://yoururl.com/somelinks?q=fill_with_random_number
for me, it works
I highly recommend not using meta tags and use htaccess as Murali Krishna Bellamkonda posted. That will always be the best and most secure dependable way. You can fine tune your whole system to stay cached for long times, refresh files at specific times, etc...
Go ahead and try all them meta tags at once, and see what happens! (no I wouldnt)
Look into Header set Cache-Control "max-age=5, immutable" with ExpiresDefault A5 for a no cache option.