How to prevent a website from being loaded in an iframe
Today we will show you how to prevent a website from being loaded in an iframe. The X-Frame-Options
HTTP response header can be used to block a website from loading in iframe.
Checkout more articles on JavaScript|PHP/ReactJS
There are three different possible values for X-Frame-Options
:
DENY
– The page cannot be displayed in a frame, regardless of the site attempting to do so.SAMEORIGIN
– The page can only be displayed in a frame on the same origin.ALLOW-FROM uri
– The page can only be displayed in a frame on the specified origin.
Multiple ways to prevent a website from being loaded in an iframe
- Using
meta
tag - Configuring Apache
- Configuring nginx
- Configuring IIS
- Configuring HAProxy
- Configuring Express
- Configuring .htaccess
1. Using meta
tag
Use the following meta tags to prevent the access.
Deny access from an iframe for all
1 | <meta http-equiv="X-Frame-Options" content="deny"> |
Deny access from other websites
1 | <meta http-equiv="X-Frame-Options" content="sameorigin"> |
Note: Setting X-Frame-Options inside the <meta>
element is useless! For instance, <meta http-equiv="X-Frame-Options" content="deny">
has no effect. Do not use it! X-Frame-Options
works only by setting through the HTTP header, as in the examples below.
2. Configuring Apache
To configure Apache to send the X-Frame-Options
header for all pages, add the following code to your site’s configuration.
1 | Header always set X-Frame-Options "SAMEORIGIN" |
Use the following code to configure Apache to set the X-Frame-Options
DENY.
1 | Header set X-Frame-Options "DENY" |
3. Configuring nginx
Similarly use the following code for the nginx configuration.
1 | add_header X-Frame-Options SAMEORIGIN always; |
4. Configuring IIS
Use the following code to update the configuration for IIS server.
1 2 3 4 5 6 7 8 9 10 11 | <system.webServer> ... ... <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="SAMEORIGIN" /> </customHeaders> </httpProtocol> ... ... </system.webServer> |
5. Configuring HAProxy
Let’s use the following code to configure HAProxy.
1 | rspadd X-Frame-Options:\ SAMEORIGIN |
For newer versions
1 | http-response set-header X-Frame-Options SAMEORIGIN |
6. Configuring Express
We need to use the helmet to update configuration in the express server.
1 2 3 | const helmet = require('helmet'); const app = express(); app.use(helmet.frameguard({ action: 'SAMEORIGIN' })); |
7. Configuring .htaccess
To manage the same type of configuration in PHP, you can also use the .htaccess file. Add the following code in your file.
1 2 3 | <IfModule mod_headers.c> Header always set X-Frame-Options "SAMEORIGIN" </IfModule> |
After successful configuration, when you load the website into the iframe, you will see the X-Frame-Options as shown in the image below.
Check this link for more information about the X-Frame-Options.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂