Introduction
When a web server denies access to a particular webpage or web content, it displays the 403 Forbidden error. Different web servers report different variations of the 403 Forbidden error.
In this article, you will learn what a 403 error is and how to fix it.
The 403 Forbidden error happens when a web server denies access to a webpage to a user trying to access it trough a web browser. The name «403 error» derives from the HTTP status code that the web server uses to describe that type of error.
There are several variations of the error and several reasons why the web server has denied access. The following sections deal with the different ways the error is displayed and its causes.
Common 403 Error Messages
Like with other errors, webmasters can customize how the 403 error is displayed. Its contents also depend on the web server used. That is why there are many different 403 pages across different websites.
Some common 403 error messages are:
- 403 Forbidden
- HTTP 403
- Forbidden
- HTTP Error 403 – Forbidden
- HTTP Error 403.14 – Forbidden
- Error 403
- Forbidden: You don’t have permission to access [directory] on this server
- Error 403 – Forbidden
- 403 Forbidden Error
- 403 Error
The image above shows an example of a 403 Forbidden error served by an Nginx web server.
What Causes the 403 Forbidden Error
The 403 Forbidden error usually occurs due to access misconfiguration. The misconfiguration involves improper read, write, or execute permission settings for a file or directory.
Possible causes for the 403 Forbidden error are:
- An empty website directory. If there is no index.php or index.html page, the 403 error displays.
- Missing index page. The 403 error may occur if the homepage name isn’t index.html or index.php.
- Permission/ownership errors. Incorrect permission settings or ownership cause the 403 error.
- Incorrect .htaccess file settings. The .htaccess file holds important website configuration settings, and it could be corrupted.
- Malware infection. If your files are infected with malware, it can keep corrupting the .htaccess file.
- Cached outdated webpage. The 403 error comes up if the page link has been updated, which is now different from the cached version.
- Faulty plugin. Improperly configured WordPress plugins or their incompatibility could trigger the 403 error.
The following section deals with different ways of fixing the 403 Forbidden error.
How to Fix the 403 Forbidden Error (Tips for Webmasters)
You can do several things to fix the 403 Forbidden error, depending on whether you are a website visitor or a webmaster.
The following fixes for the 403 Forbidden error are resources for site webmasters:
Check Website Directory
An empty website directory may cause the 403 error. Make sure that the content is in the correct directory on the server.
Depending on the server you are using, the correct directory for your content is:
- For Nginx: /var/www/vhosts/domain.com/httpdocs/
- For Apache: /home/username/public_html/
If there is no such directory, create one.
Add an Index Page
The website homepage by default is index.html or index.php. If there is no such page on your website, the visitors can encounter a 403 Error. Resolve this by uploading an index page to your httpdocs or public_html directory.
If you already have a homepage named other than index, you can rename it or set up a redirect in your .htaccess file to that homepage.
Warning: Be careful when editing the .htaccess file as it contains server configuration instructions and affects your web server’s behavior. The file is usually hidden as a precaution, but you can find it in your public_html directory by checking the Show Hidden Files option.
To redirect to your homepage, follow the steps below:
1. Log in to cPanel and navigate to your public_html directory.
Note: You can also download and edit the .htaccess file locally using an FTP client instead of cPanel.
2. Right-click the .htaccess file and choose Edit from the dropdown menu.
3. Redirect the index.php or index.html file to your existing homepage by inserting the following code snippet:
redirect /index.html /homepage.html
Replace homepage.html
with the actual name of your page.
Check File and Directory Permissions
Each file and directory on your website have permissions that control access to those files and directories. Incorrect file or directory permissions can cause the 403 Forbidden error. The permissions specify who has read or write access to the file or directory in question.
The permissions are represented with numeric values. The general practice is to use:
- 755 for directories
- 644 for static content
- 700 for dynamic content
Note: Linux file permissions can include numbers, letters, or words, as well as an entry stating to whom the file has been assigned — Owner, Group, or Both.
You can change file permissions recursively with the chmod command. If you prefer a GUI, use an FTP client to change file or directory permissions.
Create a New .htaccess File
A 403 error can be the result of improper .htaccess file configuration. The .htaccess file controls the high-level website configuration.
Follow the steps below to check if the .htaccess file is the cause of the 403 error:
1. Find the .htaccess file via your file management software (e.g., cPanel) or via an sFTP or FTP client.
2. Right-click the .htaccess file and select Download to create a local backup.
3. Next, click Delete to delete the file.
4. Visit your website. If the 403 error no longer appears, it means that the .htaccess file was corrupt.
5. Now you need to generate a new .htaccess file. Log in to your dashboard and click Settings > Permalinks.
6. Don’t make any changes. Just click the Save Changes button to create a new .htaccess file.
Visit your website to check if the error is fixed.
Enable Directory Browsing
If the website shows a 403 error when you’re trying to browse a directory, you may need to enable directory browsing in your web server software. You can turn on directory browsing in the config file. If you don’t feel confident editing the config files yourself, seek help from a web master or your hosting provider.
The following examples show how to enable directory browsing in different web servers:
- IIS Express
1. Open the Web.config file of your project.
2. Add the following tags within <system.webServer>
:
<directoryBrowse enabled="true" />
<modules runAllManagedModulesForAllRequests="true" />
- Nginx
Change the autoindex
value to on
in the config file:
The following is an example of the config file with the on
value for autoindex
.
server {
listen 80;
server_name phoenixnap.com www.phoenixnap.com;
access_log /var/...........................;
root /path/to/root;
location / { index index.php index.html index.htm; }
location /somedir { autoindex on; }
}
Apache
You have to specify the DirectoryIndex directive in the site’s .conf file (found in /etc/apache2/sites-available on Linux).
Turn on directory browsing in the Options
directive. Following is an example of the .conf file with directory browsing turned on:
<Directory /usr/local/apache2/htdocs/listme>
Options +Indexes
</Directory>
Contact the Hosting Company
The reason for the 403 Forbidden error could be with the hosting company and not with you. If everything else fails to remove the error, get in touch with your hosting company and let them check what could be causing the issue.
Disable WordPress Plugins
Sometimes, a faulty or incompatible plugin is what causes a 403 forbidden error. You can try to fix the error by disabling all plugins to check if the error goes away.
Follow the steps below to disable all plugins:
1. Log into the WP Admin and navigate to Plugins > Installed Plugins.
2. Select all plugins, choose Deactivate from the drop-down menu and click Apply.
3. Try to access your website. If there is no 403 forbidden error, that means that the cause was one of the plugins.
4. Now enable one plugin at a time to determine which one is causing the 403 error. When you find the root of the problem, update or remove the plugin or install an alternative one to resolve the issue.
Check the A Record
One of the reasons for the 403 Forbidden error can be a domain name pointing to the wrong IP address, where you don’t have the permission to view the content. This happens when the A record of a migrated website still points to the old IP address.
Follow the steps below to check if the domain A record points to the right IP address:
1. Log in to cPanel.
2. In the Domains section, click DNS Zone Editor.
3. In the list of DNS records, find the record with the A label in the Type column.
4. Check if the A record IP address in the Record column is correct. If it’s wrong, click Edit to change it.
5. Click Update to finish.
Revisit the website to see if the issue has been resolved.
Scan for Malware
Having malware on your web server can cause the 403 Forbidden error. The malware can keep injecting unwanted lines into the .htaccess file, and that way the error persists even if you generate a new .htaccess file.
Use a security plugin to scan your web server for malware and remove it if any is found. Most plugins also offer actions when detecting malware infected files, such as deleting the infected file or restoring it.
Some of the best security plugins for WordPress are Sucuri, Wordfence, Defender, etc.
How to Fix the 403 Forbidden Error (Tips for Site Visitors)
If you are a site visitor that has encountered the 403 error, below is a list of things you can try to fix the issue.
Check URL
A wrong URL is a common cause of the 403 Forbidden error. Make sure that you’re trying to access an actual webpage instead of a directory.
Many websites don’t allow visitors to browse through directories, so if you are trying to acces a directory, you will likely get a 403 Forbidden error.
Clear History/Cache
Your browser stores cached webpages to load them faster the next time you visit them. Sometimes the website link has been updated, making the actual link different from the cached version. Loading the cached version then results in a 403 error.
The stored cookies on your browser can also cause the 403 error. If the cookies are invalid or corrupted, they can cause improper server authentication. Clearing browser cache and cookies should resolve this issue.
Note: Clearing the browser cache and cookies means that the next time you load the webpage, your browser requests all the site files again, making it load slower. Clearing the cookies also signs you out from all logged-in websites.
Follow the steps below to clear the cache and cookies on Google Chrome:
- Click the three-dot button on the top right corner and select Settings.
2. Find the Privacy and security section and click Clear browsing data.
- In the drop-down menu, select the data deletion time frame.
- Check the Cookies and other site data and Cached images and files options and click Clear data.
Try to reload the site to see if the problem persists.
Log in
A 403 Forbidden error code could sometimes appear because you need to log in to a website to access a page. If possible, log in with your credentials to gain access to the content.
Note: Although the 401 error is usually displayed when you need special permission to access content, sometimes the 403 Forbidden error is displayed instead.
Reload the Page
Sometimes, reloading the page is the trick to getting around the 403 Forbidden error. Each browser has its own reload button near the address bar. Press Ctrl+F5 on Windows and Linux or Cmd+Shift+R on Mac to reload the page if you prefer using the keyboard.
Try Later
If you aren’t the only one denied access to the website, then the problem is usually with the host. Revisit the site later and see if the issue has been resolved.
Contact Your ISP
If you cannot get around the 403 error on a website, but it works for other people, contact your internet service provider (ISP).
Your IP address could be added to a blocklist, and it is causing the 403 forbidden error. In that case, your ISP cannot help you, and the only way to access the website is to use a VPN.
Conclusion
High website availability provides the best user experience and shows reliability. That is why website owners try to keep their site available at all times and invest in website maintenance services.
Preventing or quickly resolving HTTP errors is crucial if you want to retain your visitors. After reading this guide, you should be able to promptly fix the 403 Forbidden error and keep your business running.
Table of Contents
- Introduction: What is a 403 Error?
- Firewall Rules
- 403 on an Image or File
- Caching and Nonces
- File Permissions
- CDN Issues
- Corrupt/Misconfigured .htaccess file
- Broken/Missing Plugins
- Custom Nginx Config Rules
Introduction: What is a 403 Forbidden Error?
The 403 Forbidden error occurs when a request is made the server cannot allow. This is often due to a firewall ruleset that strictly prohibits this specific request, but other settings such as permissions may prevent access based on user rights.
When 403s occur, your server understands the request that is being made, but is refusing to comply with the request.
That’s about all there is to it. Your request is forbidden.
Error Messaging
On Nginx a 403 looks as follows: 403 Forbidden – nginx
Other variations of a 403 include:
- 403 – Forbidden: Access is denied
- Error 403 – Forbidden
- 403 – Forbidden Error – You are not allowed to access this address
- HTTP Error 403 – Forbidden – You do not have permission to access the document or program you requested
- 403 Forbidden – Access to this resource on the server is denied
Note
The following are all certainly possibilities for your 403 errors, however, in 90% of cases, 403 errors are caused by a firewall, caching issue, or permissions issue.
1. Firewall Rules
By far the most common reason for 403 errors is that the request you’re making is being blocked for breaking one of the firewall rules.
Unlike most other hosting providers, GridPane equips you with 1-3 different Web Application Firewall (WAF) options depending on your plan: –
- 6G WAF
- 7G WAF
- ModSecurity
Usually, 403s are a good thing. In most cases, these types of requests are malicious in nature and the firewall blocks those from even reaching your application (WordPress website). However, WordPress is a vast ecosystem of different functionality and false positives can and do occur.
The quickest way to discover if your 403 error is being caused by a WAF is to simply turn it off and try to reproduce the issue. If the 403 no longer occurs, this is a WAF issue.
You can find out the specific reason the request is being blocked by checking the log. This is available directly inside the security tab at the bottom of the settings.
Once you know the cause, you can begin crafting an exclusion that is fairly straightforward, and fully documented in the links above.
Example
Here’s an example of a request that resulted in a 403 error with the 7G WAF:
website.com/wp-admin/admin.php?page=seopress-google-analytics&code=4/0AY0eSoaWlA&scope=https://www.googleapis.com/auth/analytics.readonly
This request broke 2 rules, as detailed by this result in the 7G WAF log:
[17/Nov/2020:15:05:35 +0000] [":bad_querystring_12::bad_request_15:"] 199.199.199.199 yourdomain.com "GET /wp-admin/admin.php?page=seopress-google-analytics&code=4/0AY0e-g44ZrE9024kffJQ2LbRdRxVLOQgAruyU9wAHI1jYFCDaUo10xmwW5rpilPzqNKOSoaWlA&scope=https://www.googleapis.com/auth/analytics.readonly HTTP/1.1" 403 "https://accounts.google.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
Using this information we can create a rule to exclude these two results by targeting “page=seopress-google-analytics&code
” and adding an exclusion for both errors like so:
set $exclusion_rule_match ""; if ( $args ~* ^page=seopress-google-analytics&code ) { set $exclusion_rule_match 15; } if ($bad_request_7g = $exclusion_rule_match) { set $7g_drop_bad_request 0; }
set $exclusion_rule_match ""; if ( $args ~* ^page=seopress-google-analytics&code ) { set $exclusion_rule_match 12; } if ($bad_querystring_7g = $exclusion_rule_match) { set $7g_drop_bad_query_string 0; }
Please see the full articles for a complete tutorial.
403 on an Image or File
Following on from the above section, images or files may sometimes return a 403 for a seemingly unknown reason.
These can be difficult to troubleshoot because it’s really not obvious what the cause is, however, this is almost certainly either the 7G firewall.
A couple of examples to illustrate this are images/files that contain either the word “Specialist” or the word “Conference”.
The reason these get flagged are due to the word conference containing “conf” (which is a file name extension), and specialist containing the name of a commonly spammed pharmaceutical.
The quickest solution is to rename the file, or to edit out that specific line or word in the firewall. Our documentation has details how to do this here:
Using the GridPane 7G Web Application Firewall
2. Caching and Nonces
The second most common issue outside of a firewall rule being is broken is where caching is interfering with a form (such as a contact form, or payment gateway form). Here, the form uses what’s called a “nonce” (a security token which is a number or random string used only once), which exists for a set period of time (12 hours is common) after which it changes to something new. Once change occurs, the cache may serve the outdated nonce and this results in an error.
If you have a form or any functionality that makes use of a nonce, these can break and return 403 errors if the cache isn’t cleared once the nonce expires.
In many cases, nonces last 12-24 hours. For example, the Gravity forms payment gateway has a 12-hour nonce and can result in 403 errors if cached for over 12 hours.
If clearing the cache allows your functionality to begin operating correctly again, this is a caching issue.
Plugins we know of that may experience cache related issues are:
- Gravity Forms Payments
- Divi Forms
- Caldera Forms
In these cases, there are a couple of different solutions.
Solution 1. Exclude the page from the cache
If you exclude the page from the cache, the cache will not interfere with the nonce and all forms will operate as normal.
Please see the following guide on how to exclude a page from your website’s cache (Nginx only):
Exclude a page from server caching
Solution 2. Reduce Cache TTL
If you’re using Redis Page Caching, the default TTL is 30 days. If you’re experiencing nonce related form failures, you can reduce the cache time to avoid these in the future.
This requires running a single GP-CLI command. To do so, you will need to SSH into your server. Please see the following guides to get started:
The command for altering the default caching TTL is as follows:
gp stack nginx redis -site-cache-valid {accepted.value} {site.url}
Run the following command to reduce cache time to 6 hours (replacing site.url with your domain name):
gp stack nginx redis -site-cache-valid 21600 site.url
The time length has to be entered in seconds. In this case, 6 hours = 21600 seconds.
For 10 hours, run the following:
gp stack nginx redis -site-cache-valid 36000 site.url
For more details, please see this Redis Page caching section in the Configure Nginx article:
Set caching expiry time for all successful requests going into Redis SRCache page cache
3. Permissions
403 errors can also be caused by incorrect permissions settings. This can sometimes occur when migrating a website over to GridPane.
Fortunately, we have a quick fix self-help tool that can help reset your website to the correct permissions very quickly and with minimal fuss. To fix your websites permissions, please see this article:
Self Help Tools: Reset Application File Permissions
4. CDN Issues
If the 403 forbidden errors you’re experiencing are specific to your assets (images, CSS, and JS files), and you’re using a delivery network (CDN) for your website, try temporarily disabling this service to see if this is at the root of your issue.
If it isn’t, this is likely firewall related, possibly due to 7G Bad Bot rule #5.
5. Corrupt/Misconfigured .htaccess File
Nginx doesn’t use .htaccess
, so this error is OpenLiteSpeed specific for GridPane hosted websites.
This is a very powerful file, and if corrupted or misconfigured, this could result in a 403 error for your website.
Fortunately, GridPane keeps a backup copy that you can use in the case of an emergency:
You can get your website back up and running by replacing the current .htaccess
file with the contents of the .htaccess.save
file.
This is easier done over SFTP. To connect to your server over SFTP, please see either one of the following articles:
Connect to a GridPane Server by SFTP as System User
Connect to a GridPane Server by SFTP as Root user
Step 1
Once connected, first save a copy of the .htaccess.save
file to your computer.
Step 2
Next, rename the corrupt .htaccess
file to .htaccess.bad
Step 3
Next, rename .htaccess.save
to .htaccess
and then check your website.
Step 4
You can now re-upload the .htaccess.save
to your server again for safekeeping, and delete the .htaccess.bad
file.
6. Broken/Missing Plugin Files
If none of the above is the cause for your 403 error, then this could be the work of a broken or missing plugin file.
To check, connect to your server over SFTP (see the links in part 5 above to get started) and rename the plugins folder (located at site.url/htdocs/wp-content/plugins) to plugins-off.
Next, check your website and see if the 403 error is occurring. If not, then you know the root cause is one of the plugins on your website.
Rename the plugins-off directory back to plugins, and then do the same for each of your individual plugin folders, renaming them one by one until you find the one responsible.
7. Custom Nginx Configurations
Sometimes plugin authors can be rather careless with their Nginx recommendations, documenting broad Nginx rules that can result in unexpected/undesirable behavior such as blocking specific types of files altogether, or blocking them when not logged into the website.
You may have added custom configuration rules to Nginx via .conf files in your /var/www/site.url/nginx
directory.
For example:
/var/www/example.com/nginx/ithemes-security-main-context.conf
Custom configurations that affect ALL websites on the server may also have been added in these directories:
/etc/nginx/extra.d/
/etc/nginx/conf.d/
Be sure to check this directory for any Nginx configuration files that you or your team members may have added (be sure to ask them so you know what to look for), and review them for code that could prevent access to page or file that your getting your 403 forbidden error.
Imagine this – you’ve recently created a new website to host your content, and you’re excited to see it go live. You can’t wait to dive into SEO and begin ranking for keywords and attracting an audience to your brand.
But then a friend emails you and says, «Hey, is there a reason I see this when I click on your website? «
Image Source
Undoubtedly, a «403 Forbidden» message is cause for immediate concern. How many potential viewers are you losing, as they come across your website to find this message?
Fortunately, there are a few quick-and-easy solutions to a 403 error. Here, we’ll explain the top three, so you can get your site up and running.
A 403 Forbidden error is an HTTP status code sent to users by an HTTP server when a user tries to access a restricted URL. It means the page you were trying to reach is forbidden for one of two reasons: Either there is a removal or restriction of access permissions from the client-side, or there’s an accidental misconfiguration of the web server.
What you’ll typically see when you land on a page with a 403 forbidden error is something like this: «You don’t have authorization to view this page – HTTP Error 403.»
It can also have slightly different wording, like the example below.
Image Source
Wondering about the difference between a 403 and 404 error? Here it is: A 404 error happens when you access a page that no longer exists or cannot be found. A 403 error, on the other hand, indicates that your access has been denied due to incorrect credentials.
An easy way to remember it: 403 says «access denied» while 404 says «We can’t find what you asked for.»
What causes a 403 error?
There are a few reasons why you may see a 403 forbidden error. Here are the most common:
- Permission or ownership error – Permissions are represented by codes, which indicate what each type of user can do. If you have the incorrect code associated with a file or directory then your users may run into a 403 error.
- Wrong file or folder location – When uploading content to your site, you may have added it to the wrong directory, which is not accessible to your end-users.
- No index page – If your homepage doesn’t have an index page, it will not display correctly on a browser.
- Misconfigured WordPress plugin – A plugin may be blocking IP addresses to avoid malware, causing the 403 forbidden error.
Now that you know the causes, let’s address how to fix them.
How to Fix 403 Errors
1. Set the correct file permissions.
If you’ve configured your web server, you’ll want to add the server to the www-data group, and set ownership of /var/www to the www-data user and www-data group.
Then, make sure your directories are set to 755, your files are set to 644, and your dynamic content is set to 700. This determines which user types (owner, group, everyone) can read, write, and execute.
2. Make sure you have an index page.
Your website’s home page must be called index.html or index.php – if it’s not, you should rename the homepage to include one of those URL names.
Alternatively, you can upload an index page to your httpdocs directory and then set up a redirect on the index page to your real homepage.
3. Upload your website content to the correct directory on your server.
You might see a 403 forbidden message if you haven’t correctly uploaded your content to the directory on your server.
There are several different FTP clients you might’ve chosen to host your domain — let’s say you chose FileZilla, which is free and available for Windows, Mac, and Linux.
To publish your content online, you’ll need to put your files into the public/htdocs directory.
Note: If you’re using FileZilla, these instructions will vary if you use a different FTP client. Once you’ve dragged and dropped your files into the directory, you should search your website’s URL to double-check they now appear online.
If you’re in your FTP server and don’t see the httpdocs directory, you can create a file within the directory with this title, which could also solve the issue.
4. Deactivate and reactivate your plugins.
If you suspect one of your plugins is responsible for the 403 forbidden error, temporarily deactivate all of your plugins.
You may have noticed the error shortly after installing a plugin. If so, start with that one and work your way down from the most recent installation to the oldest.
Then, one by one, activate each plugin and refresh the page to determine which plugin is causing the error.
As you can see, 403 errors can typically be resolved in just a few easy steps. It’s just about knowing where to look.
Jun 22, 2022 7:41:27 AM |
403 Forbidden Error: What It Is and How to Fix It
A detailed explanation of what a 403 Forbidden Error response is, including troubleshooting tips to help you resolve this error.
The 403 Forbidden Error is an HTTP response status code that indicates an identified client does not have proper authorization to access the requested content. As with most HTTP response codes, a 403 Forbidden Error can be challenging to diagnose and resolve properly.
With a pool of over 50 potential status codes representing the complex relationship between the client, a web application, a web server, and often multiple third-party web services, determining the cause of a particular status code can be a challenge under the best of circumstances.
This article will examine the 403 Forbidden Error in more detail. We’ll look at what causes this message, along with a handful of tips for diagnosing and debugging your own application. We’ll even examine a number of the most popular content management systems (CMSs
) for potential problem areas that could cause your own website to be generating a 403 Forbidden Error. Let’s dive in!
Server- or Client-Side?
All HTTP response status codes in the 4xx
category are considered client error responses. These messages contrast with errors in the 5xx category, such as the 502 Bad Gateway Error. 500 errors are considered server error responses.
That said, the appearance of a 4xx error doesn’t necessarily mean the issue has something to do with the client (the web browser or device used to access the application). Oftentimes, if you’re trying to diagnose an issue with your own application, you can ignore most client-side code and components. This includes HTML, cascading style sheets (CSS), client-side JavaScript, etc. This doesn’t apply just to websites, either. Behind the scenes, normal web applications power smartphone apps that use a modern-looking user interface.
Although the 403 Forbidden Error is considered a client error response, you shouldn’t rule out the server as the culprit. The server network object is producing the 403 Error and returning it as the HTTP response code to the client. On the other hand, this doesn’t rule out the client as the actual cause of a 403 Forbidden Error, either. The client might be trying to access an invalid URL, the browser could be failing to send the proper credentials to the site, and so forth. We’ll explore some of these scenarios (and potential solutions) below.
Start With a Thorough Application Backup
Before making changes to your application, make sure to back up your system. This might include a full backup of your application, database, and so forth.
If you have the capability, create a complete copy of the application onto a secondary staging server that isn’t «live» or available to the public. This will allow you to test all potential fixes without threatening the security of your live application.
Diagnosing a 403 Forbidden Error
As previously mentioned, many 403 Forbidden Errors involve the server denying authorization to a client (a web browser, in most cases) that has requested content.
This typically occurs in one of two scenarios:
- The client sent its authentication credentials to the server and the server authenticated that the client was valid. Yet, the server rejected the authorized client from accessing the requested content for some reason.
- The requested content is strictly forbidden for all clients, regardless of authorization. This occurs when attempting to access an invalid or forbidden URL that the web server software has restricted. For example, Apache servers return a 403 Forbidden Error when a client tries to access a URL corresponding to a file system directory.
Troubleshooting on the Client-Side
Since the 403 Forbidden Error is a client error response code, start troubleshooting any potential client-side issues first.
Here are some troubleshooting tips you can try on the browser or device that is giving you problems.
Check the Requested URL
The most common cause of a 403 Forbidden Error is simply inputting an incorrect URL. As discussed before, many tightly secured web servers disallow access to improper URLs. This could be anything from accessing a file directory to accessing a private page meant for other users. Thus, it’s a good idea to double-check the exact URL that is returning the 403 error.
Clear Relevant Cookies
As you may already be aware, HTTP copies store tiny pieces of data on your local device. The website then uses these cookies to to «remember» information abbot a particular browser and/or device.
As you may already be aware, HTTP cookies store tiny pieces of data on your local device. The website then uses these cookies to «remember» information about a particular browser and/or device. Most modern web apps take advantage of these cookies to store user authentication status.
Invalid or corrupted Cookies can cause improper authentication for the server, leading to the 403 Error. This is due to the fact that the client is no longer authenticated to perform this particular request.
In most cases, you should only worry about cookies relevant to the website or application causing issues. The application stores cookies based on where the domain is located. This means you can only remove cookies that match the website domain (e.g. airbrake.io
) to keep most other cookies intact. However, if you aren’t experienced with manually removing certain cookies, remove all cookies at once. Not only is this easier, but it’s also a safer option.
Below, we’ve provided a list on how to clear cookies depending on the browser you’re using:
- Google Chrome
- Internet Explorer
- Microsoft Edge
- Mozilla Firefox
- Safari
Clear the Cache
Just like cookies, it’s also possible that the local browser cache could be causing the 403 Forbidden Error to appear.
A cache stores local copies of web content on your device for later use. A browser’s cache can include almost any type of data but typically stores compressed snapshots of webpages, images, and other binary data your browser often accesses. With a local copy of these resources on your device, your browser doesn’t need to spend time or bandwidth downloading this identical data every time you return to the same page. For example, when you open Facebook, there’s a good chance that the content you’re seeing has come from the cache on your device.
Since your browser’s cache stores local copies of web content and resources, it’s possible that a change to the live version of your application is conflicting with the cached version already on your device, which can sometimes produce a 403 Forbidden Error
as a result. Try clearing your browser’s cache to see if that fixes the issue.
As with cookies, clearing the cache is browser-dependant, so here are a few links to that relevant documentation for the most popular browsers:
- Google Chrome
- Internet Explorer
- Microsoft Edge
- Mozilla Firefox
- Safari
Log Out and Log In
If the application you’re using has some form of user authentication, the last client-side step to try is to log out and then log back in. If you’ve recently cleared the browser cookies, this should usually log you out, so the next time you try to load the page, just log back in at this point.
In some situations, the application may be running into a problem with your previous session, which is just a string that the server
sends to the client to identify that client during future requests. As with other data, your device should have stored the session token (or session string) locally on your device within the cookies. The client then transfers this data to the server during every request. If the server fails to recognize the session token or the server sees this particular token as invalid, this may result in a 403 Error.
But, with most web applications, you can recreate the local session token by logging out and logging back in.
Debugging Common Platforms
If you’re running common software packages on the server that is responding with the 403 Forbidden Error, you may want to start by looking into the stability and functionality of those platforms first. The most common content management systems (CMS) — like WordPress, Joomla!, and Drupal — are all typically well-tested out of the box, but once you start making modifications to the underlying extensions or PHP
code (the language in which nearly all modern content management systems are written in), it’s all too easy to cause an unforeseen issue that results in a 403 Error.
Here are a few tips to help you troubleshoot some of these popular software platforms:
Rollback Recent Upgrades
If you recently updated the CMS itself just before the 403 Forbidden Error appeared, you may want to consider rolling back to the previous version you had installed when things were working fine. Similarly, any extensions or modules that you may have recently upgraded can also cause server-side issues, so reverting to previous versions of those may also help.
For assistance with this task, simply Google «downgrade [PLATFORM_NAME]» and follow along. In some cases, however, certain CMSs don’t provide a version downgrade capability, which indicates that they consider the base application, along with each new version released, to be extremely stable and bug-free. This is typically the case for the more popular platforms.
Uninstall New Extensions, Modules, or Plugins
Depending on the particular CMS your application is using, the exact name of these components will be different, but they serve the same purpose across every system: improving the capabilities and features of the platform beyond what it’s normally capable of out of the box. Be warned: such extensions can, more or less, take full control of the system and make virtually any changes, whether it be to the PHP code, HTML, CSS, JavaScript, or database. As such, try uninstalling any recently added extensions. Again, Google the extension name for the official documentation and assistance with this process.
Check for Unexpected Database Changes
Uninstalling a CMS extension does not guarantee that changes will fully revert. This is particularly true for WordPress extensions. These extensions have carte blanche status within an application, which allows them full access rights to the database. With this access, an extension can modify database records that don’t «belong» to the extension itself. That means it can change records created and managed by other extensions of the CMS itself.
In those scenarios, the extension may not know how to revert alterations to database records, so it will ignore such things during uninstallation. Diagnosing such problems can be tricky. Your best course of action, assuming you’re reasonably convinced an extension is the likely culprit for the 403 Forbidden Error,
is to open the database and manually look through tables and records that were likely modified by the extension.
Confirm Proper File Permissions
If the application worked fine before and suddenly this error occurs, permissions are not a very likely culprit. However, if modifications were recently made (such as upgrades or installations), it’s possible that file permissions were changed or are otherwise incorrect, which could cause an issue to propagate its way throughout the application and eventually lead to a 403 Forbidden Error. The majority of servers use Unix-based operating systems.
In this Wikipedia article, File-System Permissions, you’ll learn more about how to set up proper permissions for application files and directories to keep your application secure without hindering your applications’ access.
Above all, Google is your friend. Search for specific terms related to your issue, such as the name of your application’s CMS, along with the 403 Forbidden Error. Chances are you’ll find someone (or, perhaps, many someones) who have experienced this issue and have found a solution.
Troubleshooting on the Server-Side
If you’re confident that your CMS isn’t the problem, a 403 Error could be a result of a server-side issue.
Troubleshoot the server with these tips.
Check Your Web Server Configuration
Most modern web servers provide one or more configuration files to adjust server behavior. These configurations are based on a wide range of circumstances. For example, the server may be configured to reject requests to certain directories or URLs, which could result in a 403 Error.
Configuration options for each different type of web server can vary dramatically. Here is a list of a few popular ones to give you some resources to look through:
- Apache
- Nginx
- IIS
- Node.js
- Apache Tomcat
Look Through the Logs
Nearly every web application will keep some form of server-side logs. Application logs contain the history of what the application did, such as which pages were requested, which servers it connected to, which database results it provided, and so forth. Server logs are related to the actual hardware that is running the application. They will often provide details about the health and status of all connected services, or even just the server itself. Google «logs [PLATFORM_NAME]» if you’re using a CMS, or «logs [PROGRAMMING_LANGUAGE]» and «logs [OPERATING_SYSTEM]» if you’re running a custom application, for more information on finding the logs in question.
Check the Database for User Authentication
As you know now, a 403 Error may indicate that the client properly authenticated at some point, but doesn’t have access to the requested resource. It’s worth checking the server to see why it denied the requested resource. Perhaps there’s an issue with the database and can’t authenticate the client.
Verify Server Connectivity
While it may sound simple, it’s entirely possible that a Forbidden Error simply indicates that a server somewhere in the chain is down or unreachable for whatever reason. Most modern applications don’t reside on a single server. Instead, applications may be spread over multiple servers or rely on third-party services to function. If any one of these servers are down for maintenance or otherwise inaccessible, this could result in an error that appears to be from your own application.
Debug Your Application Code or Scripts
If all else fails, manually debug your application by parsing through application and server logs. Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process. This will allow you to recreate the exact scenario in which the 403 Forbidden Error
occurred and view the application code at the moment something goes wrong.
But, for a faster way to debug, install Airbrake Error & Performance Monitoring. If there’s broken code that’s throwing a 403 Error, Airbrake will find it, and quickly. Create a free Airbrake dev account, today, and for the first 30-days, you’ll have access to unlimited error and performance events.
Note: We published this post in October 2017 and recently updated it in February 2022.
Ошибка 403 (error 403 Forbidden) — это ответ сервера, который отправляется, когда доступ к странице запрещен или ограничен по ряду причин.
Текстовое описание ошибки может варьироваться. Вот некоторые вариации:
- 403 Forbidden.
- Access denied.
- «В доступе отказано».
- Forbidden.
- You don’t have permission to access.
- Запрещено 403.
Перепутать ошибку с другими сложно, так как на странице обязательно будет указан код ошибки 403.
Как исправить ошибку 403
Почему возникает ошибка? Самый частый вариант — у пользователя недостаточно прав для просмотра страницы или контента на ней. Запрет с кодом 403 может установить администратор сети, администратор сервера, провайдер или разработчик.
Чаще всего причины появления ошибки связаны с проблемами на стороне сайта. Ниже отметим самые распространенные причины ошибки и расскажем, как исправить ситуацию.
Не успел обновиться кэш DNS серверов
Эта проблема часто возникает при переносе домена между разными регистраторами, а также при попытках перенести домен на разные аккаунты у одного регистратора.
Решение: подождать. Обновление DNS записей, как правило, может занимать от 4 до 24 часов.
Ошибку вызывает плагин
Вспомните, какие плагины вы устанавливали в последнюю неделю. Если найти виновника таким образом не удается, можно начать отключать каждый плагин по отдельности, поочередно проверяя доступность проблемной страницы.
Решение: найти проблемное расширение и отключить его.
Доступ к сайтам ограничен для пользователей из определенного местоположения
Одна из самых актуальных причин ошибки 403 в последние месяцы у россиян. Дело в том, что многие английские, украинские и европейские сайты начали блокировать доступ по географическому признаку. В итоге при попытке открыть любую страницу такого сайта вы увидите ошибку.
Решение: воспользоваться VPN-сервисом.
Некорректный файл индекса сайта
Одна из самых частых причин ошибки на всех страницах сайта. Суть в том, что индексный файл располагается в некорректной директории, вовсе отсутствует или имеет неправильный формат.
Индексный файл — это index.html, который используется, чтобы указать главную страницу сайта. Этот файл всегда должен находиться в корневой папке сайта.
Решение: проверить индексный файл своего сайта. Для этого откройте файловый менеджер используемого хостинга и найдите файл со словом index.
Если вы пользуетесь услугами REG.RU, там также есть встроенный файловый менеджер. Чтобы получить к нему доступ, выполните следующие действия:
- В левом навигационном меню выберите пункт «Сайты».
- Выберите проблемный домен.
- Кликните по кнопке «Менеджер файлов» (в новой версии «Файлы сайта»).
- Найдите индексный файл в корневой директории сайта.
Важно: индексный файл должен обязательно располагаться в папке, которая называется public_html.
Обязательно проверьте необходимый формат индексного файла: далеко не всегда он должен иметь расширение .HTML.
В зависимости от используемой системы управления контентом и конфигурации сайта индексный формат файла может отличаться: возможные варианты расширения — HTML, PHP, HTM.
В разных панелях управления проверка индексного файла происходит по-разному. Посмотрим, как проверить индексный файл в ISPmanager — однойиз самых популярных панелей управления сегодня.
- В навигационном меню слева нажимаем кнопку «Сайты».
- Выбираем проблемный домен, нажимаем кнопку «Изменить».
- В самом низу находим строку «Индексная страница»:
Приостановлено обслуживание сайта на конкретном хостинге
Если вебмастер вовремя не оплатил услуги хостинга, возможно появление ошибки 403 при открытии любых страниц сайта. Сайт так и останется недоступным, пока не будет погашен долг в соответствии с договором обслуживания.
Решение: оплатить услуги хостинга.
Некорректное месторасположение файлов сайта
Частая проблема, возникающая при ручном переносе файлов сайта. Здесь правило простое: файлы сайта располагаются в корневой директории.
Решение: убедиться, что папка с файлами сайта находится в правильной папке. Корневая папка сайта по управлением WordPress на хостинге Beget может выглядеть так:
Указаны некорректные права на файл или папку
Существует три вида прав доступа к файлам: чтение, редактирование, выполнение. В свою очередь, всех пользователей также можно разделить на три категории: администраторы, модераторы и обычные пользователи.
Для задания самих прав используются трехзначные коды:
- Для папок — код 755 или код 750;
- Для файлов — код 644 или код 640.
Вы можете установить любой из этих вариантов.
У разных CMS могут быть свои коды для указания прав папок и файлов. Например, в WordPress на системный файл wp-config.php должны быть настроены права с кодом 440 (или с кодом 400).
Решение: проанализировать права всех папок и изменить их при необходимости. Проверьте, какие файлы и папки загружаются при открытии страницы с 403-м ответом. Чтобы уточнить этот момент, вы можете обратиться в техподдержку хостинга.
Некорректные указания в конфигурационном файле htaccess
.htaccess — это файл конфигурации для использования на веб-серверах с программным обеспечением Apache Web Server. Когда .htaccess помещается в каталог (который, в свою очередь, загружается через веб-сервер Apache), он обнаруживается и выполняется программным обеспечением веб-сервера Apache.
Рассмотрим пример директивы, которая запрещает доступ к сайту всем пользователям, кроме одного IP-адреса:
Order Deny.Allow
Deny from all
Allow from 123.456.789.000
С такой директивой сайт будет недоступен для пользователей, так как просмотр разрешен только с одного IP-адреса.
Решение: найти файл .htaccess в папке сайта и проанализировать команды, которые были прописаны недавно.
Прежде чем редактировать файл, обязательно сделайте его резервную копию. Указанное ниже решение актуально только для хостингов на базе Linux.
Особое внимание обратите на команды со словами deny, redirect, require:
Удалите все соответствующие строки (со словами deny, redirect, require) и сохраните файл. Отключите кэширование данных на сайте и проверьте доступность страницы, которая отдавала 403-й код. Если все работает, значит причина была именно в .htaccess. Снова включите кэширование данных.
Если страница все равно не открывается, измените название файла htaccess на old_htaccess. Убедитесь, что кэширование данных на сайте отключено и снова откройте проблемную страницу. Если страница по-прежнему отдает код 403, дело точно не в htaccess и проверять нужно другие причины, которые мы описали выше.
Если ни один из вышеуказанных способов так и не помог оживить страницу, очистите кэш и удалите cookies-файлы в используемом браузере.
Иные причины 403 ошибки
- Работодатель ограничивает доступ ко всем публичным сайтам, кроме тех, которые нужны для работы.
- Доступ к сайту временно ограничен вебмастером по определенному признаку, например, по используемому браузеру.
- Допущена опечатка в URL страницы (при ручном вводе).
- Пользователь пытается открыть страницу сайта, предназначенную для служебного использования.
- Пользователь пытается открыть страницу сайта, предназначенную для использования только зарегистрированными пользователями.
- Пользователь был заблокирован по какому-либо параметру, например по IP-адресу (за нарушение правил пользования сайтом).
- Доступ к сайту временно приостановлен для всех пользователей, так как проводится его техническое обслуживание.
Резюме
Используйте чек-лист, который поможет исправить ошибку 403 вебмастеру и пользователю.
Вебмастеру
- Убедитесь, что указан корректный адрес страницы.
- Проверьте директивы в системном файле htaccess.
- Убедитесь, что все файлы сайта находятся в корневом каталоге.
- Проверьте наличие всех необходимых файлов, которые загружаются при обращении к проблемной странице.
- Свяжитесь с хостингом и уточните, имеются ли какие-либо ограничения, наложенные на ваш сайт или домен.
- Убедитесь, что выставлены корректные права доступа на папки и файлы.
Обязательно проверить логи сервера. Если 403 ответ в них упоминается, вы сможете узнать точную причину появления этой ошибки. Если же такой ошибки в логах нет, причину следует искать в скриптах, которые используются на сайте.
Пользователю
У пользователя возможности исправить ошибку гораздо меньше, так как причина, чаще всего, находится не на его стороне. Что вы можете сделать:
- Дважды проверьте URL, если указываете его вручную.
- Пройдите авторизацию, если такая возможность предусмотрена конфигурацией сайта.
- Свяжитесь с администратором сайта и сообщите об ошибке.
- Попробуйте открыть ссылку спустя 2-3 дня. Во многих случаях ошибка носит временный характер.
Часто адрес страницы меняется дважды после публикации и поисковые системы просто не успевают обработать новую версию адреса. Следует подождать хотя бы один день. Страница с некорректным URL покинет индекс, исчезнет из результатов поиска, а на ее место придет страница с правильным адресом.
В этой статье мы расскажем о причинах, с которыми может быть связано возникновение ошибки 403. В качестве примера мы покажем вам, как исправить подобную ошибку на WordPress-сайте. Тем не менее, на других CMS или статических сайтах действия, которые необходимо предпринять, будут почти аналогичными:
Причины возникновения ошибки 403 могут отличаться в зависимости от различных обстоятельств. Иногда эта ошибка может быть результатом изменений или обновлений, которые ваш хостинг произвел в своей системе.
Рассмотрим эту тему подробнее. Затем мы перечислим различные причины возникновения этой ошибки и пути решения.
Что понадобится
- Доступ к панели управления хостингом.
- Что такое ошибка доступа 403?
- Почему возникает ошибка доступа 403
- Что делать если возникла ошибка доступа 403
- Шаг 1 — Проверка файла .htaccess
- Откройте «Диспетчер файлов» в панели управления хостингом
- Шаг 2 — Работа с правами доступа
- Шаг 3 — Отключение плагинов WordPress
- Заключение
Прежде чем мы продолжим и попытаемся исправить код ошибки 403, давайте сначала поймем, что это на самом деле такое. Ошибка доступа 403 — это код состояния HTTP.
Вот примеры сообщений об ошибке, с которыми можно столкнуться:
Forbidden: You don't have permission to access [directory] on this server HTTP Error 403 – Forbidden 403 forbidden request forbidden by administrative rules 403 Forbidden Access Denied You don't have permission to access
Давайте выясним, что вызывает эти ошибки.
Получение сообщения об ошибке 403 в процессе разработки может оказаться тревожным сигналом. Причина может заключаться в том, что вы пытаетесь получить доступ к тому, к чему у вас нет прав. Ошибка доступа 403 — это способ, с помощью которого сайт заявляет, что у вас недостаточно прав.
Эта ошибка обусловлена следующим:
- Неверные права доступа к файлам или папкам;
- Неправильные настройки в файле .htaccess.
Кратко рассмотрим, как можно это исправить.
Теперь, когда мы знаем факторы, провоцирующие возникновение ошибки, пришло время рассмотреть то, как от нее избавиться.
Действия, перечисленные ниже, будут касаться исправления ошибки 403 на WordPress-сайте. Но их также можно использовать и на других платформах. Рассмотрим весь процесс обнаружения ошибки 403 доступ запрещен, и ее исправления по этапам.
Возможно, вы не знакомы с файлом .htaccess. Это потому, что файл часто остается скрытым в директории проекта. Но если вы используете Hostinger File Manager, вы видите .htaccess по умолчанию:
Если вы используете CPanel, можно найти этот файл, используя «Диспетчер файлов». Давайте рассмотрим, как это делается:
В папке public_html найдите файл .htaccess. Если вы не видите его в этой папке, можно нажать на кнопку «Настройки» и включить параметр «Показать скрытые файлы»:
.htaccess — это файл конфигурации сервера, который предназначен для изменения настроек веб-сервера Apache.
Файл .htaccess присутствует на всех WordPress-сайтах. В тех редких случаях, когда сайт не его или он был удален непреднамеренно, нужно создать этот файл вручную.
После того как вы нашли файл .htaccess, чтобы исправить ошибку 403 forbidden, нужно:
- Скачать файл .htaccess на компьютер, чтобы создать резервную копию;
- После этого удалить файл.
- Теперь попробуйте получить доступ к сайту;
- Если он работает нормально, это просто указывает на то, что файл .htaccess был поврежден;
- Чтобы создать новый файл .htaccess, войдите в панель управления WordPress и выберите пункт Настройки> Постоянные ссылки;
- Без внесения изменений нажмите на кнопку «Сохранить», расположенную в нижней части страницы.
- Таким образом, для сайта будет создан новый файл .htaccess.
Если это не решит проблему, перейдите к следующему шагу.
Еще одна причина по которой возникает ошибка http 403 — это неверные права доступа к файлам или папкам. При создании файлов для них по умолчанию задаются определенные права доступа. Они указывают, как и кто может осуществлять их считывание, запись и выполнение. Но иногда нужно изменить права доступа по умолчанию.
Это можно сделать с помощью FTP-клиента или диспетчера файлов. FTP-клиент FileZilla предоставляет больше возможностей для изменения прав доступа к файлам и папкам. Поэтому мы рекомендуем использовать его, чтобы выполнить следующие действия:
- Зайдите на свой сайт через FTP;
- Перейдите в корневой каталог;
- Выберите основную папку, содержащую все файлы вашего сайта (обычно это public_html), кликните по ней правой кнопкой мыши и выберите пункт «Права доступа к файлам»:
- Установите флажок «Применить только к папкам», укажите права 755 в поле числового значения и нажмите кнопку «OK»;
- После того, как FileZilla изменит права доступа к папкам, повторите шаг 3, но на этот раз выберите параметр «Применить только для файлов» и введите 644:
- После этого попробуйте зайти на сайт и проверьте, не решена ли проблема.
Если ничего не изменилось, пришло время перейти к следующему шагу.
Высока вероятность того, что ошибка 403 была вызвана несовместимостью или некорректной работой плагина. На этом этапе мы отключим плагины, чтобы выяснить, не с ними ли связана ошибка 403. Лучше, конечно, отключить все плагины одновременно, а не каждый по отдельности. Так вы сможете обнаружить проблему и решить ее.
Вот, что нужно сделать:
- Перейдите на хостинг через FTP и найдите папку public_html (или папку, содержащую установочные файлы WordPress);
- Перейдите в папку wp-content;
- Перейдите в папку Plugins и переименуйте ее, например в «disabled-plugins«, чтобы ее было легче найти.
После отключения плагинов попробуйте снова зайти на сайт. Проблема исправлена? Если да, то причиной ошибки является некорректно работающий плагин. Попробуйте отключить плагины один за другим. Так вы сможете его обнаружить.
Затем можно попытаться обновить плагин. Если ни один из перечисленных способов не помог, то пришло время обратиться к своему хостинг-провайдеру.
Следуя приведенным выше рекомендациям, можно избавиться от ошибки 403 forbidden.
A clear explanation from Daniel Irvine [original link]:
There’s a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization.
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a WWW-Authenticate header that describes how
to authenticate.This is a response generally returned by your web server, not your web
application.It’s also something very temporary; the server is asking you to try
again.So, for authorization I use the 403 Forbidden response. It’s
permanent, it’s tied to my application logic, and it’s a more concrete
response than a 401.Receiving a 403 response is the server telling you, “I’m sorry. I know
who you are–I believe who you say you are–but you just don’t have
permission to access this resource. Maybe if you ask the system
administrator nicely, you’ll get permission. But please don’t bother
me again until your predicament changes.”In summary, a 401 Unauthorized response should be used for missing
or bad authentication, and a 403 Forbidden response should be used
afterwards, when the user is authenticated but isn’t authorized to
perform the requested operation on the given resource.
Another nice pictorial format of how http status codes should be used.
Nick T
25.2k11 gold badges79 silver badges120 bronze badges
answered Aug 4, 2011 at 6:24
23
Edit: RFC2616 is obsolete, see RFC9110.
401 Unauthorized:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.
403 Forbidden:
The server understood the request, but is refusing to fulfill it.
From your use case, it appears that the user is not authenticated. I would return 401.
emery
8,03510 gold badges42 silver badges49 bronze badges
answered Jul 21, 2010 at 7:28
OdedOded
485k98 gold badges877 silver badges1003 bronze badges
11
Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.
Brief and Terse
Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.
Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.
Detailed and In-Depth
From RFC2616
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).
and
10.4.4 403 Forbidden
The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.
The first thing to keep in mind is that «Authentication» and «Authorization» in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use «login» to refer to authentication and authorization by methods other than RFC2617
So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.
401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let’s give it a try and see what happens.
403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help — that is outside the RFC2616 standards and definition.
Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.
answered Feb 5, 2013 at 17:14
ldrutldrut
3,7771 gold badge17 silver badges4 bronze badges
7
+----------------------- | RESOURCE EXISTS ? (if private it is often checked AFTER auth check) +----------------------- | | NO | v YES v +----------------------- 404 | IS LOGGED-IN ? (authenticated, aka user session) or +----------------------- 401 | | 403 NO | | YES 3xx v v 401 +----------------------- (404 no reveal) | CAN ACCESS RESOURCE ? (permission, authorized, ...) or +----------------------- redirect | | to login NO | | YES | | v v 403 OK 200, redirect, ... (or 404: no reveal) (or 404: resource does not exist if private) (or 3xx: redirection)
Checks are usually done in this order:
- 404 if resource is public and does not exist or 3xx redirection
- OTHERWISE:
- 401 if not logged-in or session expired
- 403 if user does not have permission to access resource (file, json, …)
- 404 if resource does not exist or not willing to reveal anything, or 3xx redirection
UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named ‘unauthenticated’ instead of ‘unauthorized’. This can also happen after login if session expired.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja) in the case that revealing the presence of the resource exposes sensitive data or gives an attacker useful information.
NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).
As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):
- Difference between HTTP redirect codes
- How long do browsers cache HTTP 301s?
- What is correct HTTP status code when redirecting to a login page?
- What’s the difference between a 302 and a 307 redirect?
answered Feb 23, 2015 at 11:00
9
According to RFC 2616 (HTTP/1.1) 403 is sent when:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead
In other words, if the client CAN get access to the resource by authenticating, 401 should be sent.
answered Jul 21, 2010 at 7:26
CumbayahCumbayah
4,3771 gold badge24 silver badges32 bronze badges
6
Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.
403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.
If HTTP authentication is not in use and the service has a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.
Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):
3.1. 401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help… or it might not.
I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today’s Web apps build custom authentication schemes using for example forms and cookies.
answered Feb 27, 2013 at 9:44
6
- 401 Unauthorized: I don’t know who you are. This an authentication error.
- 403 Forbidden: I know who you are, but you don’t have permission to access this resource. This is an authorization error.
Premraj
72.1k25 gold badges236 silver badges175 bronze badges
answered Aug 6, 2019 at 12:37
4
This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn’t have access to. Ideally you wouldn’t want a malicious user to even know that there’s a page / record there, let alone that they don’t have access. When I’m building something like this, I’ll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.
OWASP has some more information about how an attacker could use this type of information as part of an attack.
answered Dec 25, 2014 at 9:09
4
This question was asked some time ago, but people’s thinking moves on.
Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.
It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.
I’ve emphasized the bit I think is most salient.
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Whatever convention you use, the important thing is to provide uniformity across your site / API.
answered May 22, 2014 at 10:54
Dave WattsDave Watts
8407 silver badges11 bronze badges
1
These are the meanings:
401: User not (correctly) authenticated, the resource/page require authentication
403: User’s role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators.
Note: Technically, 403 is a superset of 401, since is legal to give 403 for unauthenticated user too. Anyway is more meaningful to differentiate.
answered Nov 19, 2019 at 10:17
Luca C.Luca C.
11.1k1 gold badge86 silver badges77 bronze badges
3
!!! DEPR: The answer reflects what used to be common practice, up until 2014 !!!
TL;DR
- 401: A refusal that has to do with authentication
- 403: A refusal that has NOTHING to do with authentication
Practical Examples
If apache requires authentication (via .htaccess
), and you hit Cancel
, it will respond with a 401 Authorization Required
If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden
RFC (2616 Section 10)
401 Unauthorized (10.4.2)
Meaning 1: Need to authenticate
The request requires user authentication. …
Meaning 2: Authentication insufficient
… If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. …
403 Forbidden (10.4.4)
Meaning: Unrelated to authentication
… Authorization will not help …
More details:
The server understood the request, but is refusing to fulfill it.
It SHOULD describe the reason for the refusal in the entity
The status code 404 (Not Found) can be used instead
(If the server wants to keep this information from client)
answered Feb 25, 2015 at 9:03
LeviteLevite
16.9k8 gold badges50 silver badges50 bronze badges
2
they are not logged in or do not belong to the proper user group
You have stated two different cases; each case should have a different response:
- If they are not logged in at all you should return 401 Unauthorized
- If they are logged in but don’t belong to the proper user group, you should return 403 Forbidden
Note on the RFC based on comments received to this answer:
If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:
«The request requires user authentication.»
If you’re unauthenticated, 401 is the correct response. However if you’re unauthorized, in the semantically correct sense, 403 is the correct response.
answered Oct 1, 2012 at 14:34
Zaid MasudZaid Masud
13.1k9 gold badges66 silver badges88 bronze badges
4
I have created a simple note for you which will make it clear.
answered Nov 11, 2021 at 12:19
PrathamPratham
4673 silver badges7 bronze badges
In English:
401
You are potentially allowed access but for some reason on this request you were
denied. Such as a bad password? Try again, with the correct request
you will get a success response instead.
403
You are not, ever, allowed. Your name is not on the list, you won’t
ever get in, go away, don’t send a re-try request, it will be refused,
always. Go away.
answered Apr 8, 2020 at 14:23
JamesJames
4,6155 gold badges36 silver badges48 bronze badges
2
401: You need HTTP basic auth to see this.
If the user just needs to log in using you site’s standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.
403: This resource exists but you are not authorized to see it, and HTTP basic auth won’t help.
I don’t recommend using 403 to deny access to things like /includes
, because as far as the web is concerned, those resources don’t exist at all and should therefore 404.
In other words, 403 means «this resource requires some form of auth other than HTTP basic auth (such as using the web site’s standard HTML login form)».
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
answered Sep 23, 2017 at 12:33
Vlad KorneaVlad Kornea
4,2493 gold badges38 silver badges40 bronze badges
401: Who are you again?? (programmer walks into a bar with no ID or invalid ID)
403: Oh great, you again. I’ve got my eye on you. Go on, get outta here. (programmer walks into a bar they are 86’d from)
answered Aug 11, 2022 at 23:10
emeryemery
8,03510 gold badges42 silver badges49 bronze badges
0
I think it is important to consider that, to a browser, 401 initiates an authentication dialog for the user to enter new credentials, while 403 does not. Browsers think that, if a 401 is returned, then the user should re-authenticate. So 401 stands for invalid authentication while 403 stands for a lack of permission.
Here are some cases under that logic where an error would be returned from authentication or authorization, with important phrases bolded.
- A resource requires authentication but no credentials were specified.
401: The client should specify credentials.
- The specified credentials are in an invalid format.
400: That’s neither 401 nor 403, as syntax errors should always return 400.
- The specified credentials reference a user which does not exist.
401: The client should specify valid credentials.
- The specified credentials are invalid but specify a valid user (or don’t specify a user if a specified user is not required).
401: Again, the client should specify valid credentials.
- The specified credentials have expired.
401: This is practically the same as having invalid credentials in general, so the client should specify valid credentials.
- The specified credentials are completely valid but do not suffice the particular resource, though it is possible that credentials with more permission could.
403: Specifying valid credentials would not grant access to the resource, as the current credentials are already valid but only do not have permission.
- The particular resource is inaccessible regardless of credentials.
403: This is regardless of credentials, so specifying valid credentials cannot help.
- The specified credentials are completely valid but the particular client is blocked from using them.
403: If the client is blocked, specifying new credentials will not do anything.
answered Jun 2, 2018 at 23:34
401
response means one of the following:
- An access token is missing.
- An access token is either expired, revoked, malformed, or invalid.
403
response on the other hand means that the access token is indeed valid, but that the user does not have appropriate privileges to perform the requested action.
answered Feb 17, 2022 at 11:16
Ran TurnerRan Turner
12.7k4 gold badges38 silver badges48 bronze badges
0
Given the latest RFC’s on the matter (7231 and 7235) the use-case seems quite clear (italics added):
- 401 is for unauthenticated («lacks valid authentication»); i.e. ‘I don’t know who you are, or I don’t trust you are who you say you are.’
401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not
been applied because it lacks valid authentication credentials for
the target resource. The server generating a 401 response MUST send
a WWW-Authenticate header field (Section 4.1) containing at least one
challenge applicable to the target resource.
If the request included authentication credentials, then the 401
response indicates that authorization has been refused for those
credentials. The user agent MAY repeat the request with a new or
replaced Authorization header field (Section 4.2). If the 401
response contains the same challenge as the prior response, and the
user agent has already attempted authentication at least once, then
the user agent SHOULD present the enclosed representation to the
user, since it usually contains relevant diagnostic information.
- 403 is for unauthorized («refuses to authorize»); i.e. ‘I know who you are, but you don’t have permission to access this resource.’
403 Forbidden
The 403 (Forbidden) status code indicates that the server understood
the request but refuses to authorize it. A server that wishes to
make public why the request has been forbidden can describe that
reason in the response payload (if any).
If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different
credentials. However, a request might be forbidden for reasons
unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).
answered Jun 5, 2018 at 15:26
cjbarthcjbarth
4,0526 gold badges41 silver badges60 bronze badges
3
I have a slightly different take on it from the accepted answer.
It seems more semantic and logical to return a 403 when authentication fails and a 401 when authorisation fails.
Here is my reasoning for this:
When you are requesting to be authenticated, You are authorised to make that request. You need to otherwise no one would even be able to be authenticated in the first place.
If your authentication fails you are forbidden, that makes semantic sense.
On the other hand the forbidden can also apply for Authorisation, but
Say you are authenticated and you are not authorised to access a particular endpoint. It seems more semantic to return a 401 Unauthorised.
Spring Boot’s security returns 403 for a failed authentication attempt
answered Apr 6, 2022 at 22:44
theMyththeMyth
2544 silver badges14 bronze badges
In the case of 401 vs 403, this has been answered many times. This is essentially a ‘HTTP request environment’ debate, not an ‘application’ debate.
There seems to be a question on the roll-your-own-login issue (application).
In this case, simply not being logged in is not sufficient to send a 401 or a 403, unless you use HTTP Auth vs a login page (not tied to setting HTTP Auth). It sounds like you may be looking for a «201 Created», with a roll-your-own-login screen present (instead of the requested resource) for the application-level access to a file. This says:
«I heard you, it’s here, but try this instead (you are not allowed to see it)»
answered Dec 12, 2014 at 19:01
3