问题答案 12026年5月27日 22:18
How to block website from loading in iframe?
When developing web applications, ensuring application security is a critical aspect. Preventing other websites from embedding your site via iframes is a measure to avoid clickjacking attacks. There are several methods to prevent your website from being loaded in iframes:1. Using the X-Frame-Options HTTP Response HeaderX-Frame-Options is an HTTP response header that instructs the browser whether to allow the current page to be displayed within or elements. This header has several options:: Disallows any website from displaying the page via iframe.: Allows only the same-origin domain to display the page via iframe.: Allows a specified URI to display the page via iframe.For example, if you want to prevent all websites from displaying your site via iframes, add the following code to your server configuration:2. Using Content Security Policy (CSP)Content Security Policy (CSP) is a more robust method that enhances application security by defining content security policies. Using CSP allows you to specify which resources can be loaded and executed by the browser.By setting the directive, you can control which websites can embed your page. For example, if you do not want any website to embed your site via iframe or frame, set it as follows:If you only allow the same domain to embed your page via iframe, set it as:Real-World ExampleIn a previous project, we developed an online payment platform. To protect user data from clickjacking attacks, we added to the HTTP response headers on the server. This ensures that only requests from the same domain can load our payment page via iframe, effectively reducing security risks.ConclusionBy using or , you can effectively control whether your website can be embedded in iframes on other sites, thereby enhancing website security. In actual development, it is crucial to choose the appropriate methods and strategies based on your specific requirements.