I am having my APIs (built using Laravel 8 Framework) hosted in a subdomain - webapi.somedomain.com. And am running a local version of Frontend UI built using React Framework and Axios library for the HTTP Requests. I have hosted in a Shared Hosting space (cPanel + CentOS)
I am facing an issue while hitting the hosted APIs. I have stated the error I see below:
Access to XMLHttpRequest at 'http://webapi.somedomain.com/api/authorization/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So I added the Laravel Custom CORS middleware; updated the files and cleared the cache using php artisan config:cache. Didn't work out.
Couldn't find any other resources. So I added the Laravel CORS package - fruitcake/laravel-cors. Have installed it, published it and added it to the middleware; updated the file and cleared the cache. But still I see the CORS error when hitting the APIs from my React project
config/cors.php:
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
Kernel.php:
protected $middleware = [
...
\Fruitcake\Cors\HandleCors::class,
];
Am just a beginner in Laravel. What am I doing wrong? Can someone help me out? Thanks in advance.
P.S.: I totally understand what CORS is and how it works. I m new to Laravel. Not new to development. I wanna know what else should I be doing, and whether I am leaving out something.
The issue is because of the .htaccess file.
In a shared hosting server it is important to have only the public folder of your project accessible in the public_html folder and the rest hidden in private.
Link your index.php to the autoload.php that is in private (public non-accessible place - root folder or any folder thats outside public_html)
When adding a Laravel project to a shared hosting workspace, it is important to add a few rules to the .htaccess file in the public folder which is inside the public_html folder of your hosting workspace.
Finally the .htaccess file should look something like this:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
Options +FollowSymlinks
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
Only after this you will be able to run queries to the Laravel routes. If not only the index.php will get executed and the other routes will not be recognized.
This might be a known one. But as I was a beginner, I couldn't figure this out. Adding this as the answer in case any other beginner is facing the same problem. Cheers.
If you are using apache2 to serve your laravel application then it could be an issue with the conf file of domain/subdomain which serves your application
to allow usage of .htaccess you need to add block to your conf file after block end tag. something like the following:
// File: /etc/apache2/sites-available/example.com.conf
// File: /etc/apache2/sites-available/example.com-le-ssl.conf
....
</VirtualHost>
<Directory /var/www/html/example.com/public_html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
make sure to revision your project path and make sure to include this block in both of your conf files in case your project is served with SSL [https]
Now any configuration in your .htaccess file will be applied
Add this into your .htaccess which is located with your index.php
and
Change domain name with your website name in below code(Header add Access-Control-Allow-Origin: "https://typeHEREyour.com")
Code:
For CORS Configuration
# Add Font Types
AddType application/vnd.ms-fontobject .eot
AddType application/x-font-ttf .ttf
AddType application/x-font-opentype .otf
AddType application/font-woff .woff
AddType application/font-woff2 .woff2
<IfModule mod_headers.c>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
## un-remark this one for all access and remark out the one below it
#Header set Access-Control-Allow-Origin "*"
## Change this to your local host url. and https or http
Header add Access-Control-Allow-Origin: "https://typeHEREyour.com"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
</FilesMatch>
</IfModule>
# Remove index.php from URL
RewriteCond %{HTTP:X-Requested-With} !^XMLHttpRequest$
RewriteCond %{THE_REQUEST} ^[^/]*/index\.php [NC]
RewriteRule ^index\.php(.*)$ $1 [R=301,NS,L]
Related
I developed a system with REACT and Express.
It works well in local.
When I deployed to CPanel, I got 404 error for sub routers refreshing, so I added .htaccess like this.
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
</IfModule>
After I added this, I got a CORS error when I call backend API with axios.
Please help me.
UPDATE
If I add .htaccess, I got this error.
Access to XMLHttpRequest at 'https://api.lightcoin.io/api/history?user=0x1C09d124d6c03EF63B1e0C3D1Af1b2eFE628ceE8' from origin 'https://lightcoin.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I remove .htaccess, it works well, but when the page of sub-router is refreshed, I got 404 error.
I'm using create-react-app together with react-router. How can I make any of the following variations (I don't think I missed any):
www.example.com
example.com
http://example.com
http://www.example.com
redirect to:
https://example.com (notice the https secured, and no www.)
I created an .htaccess file with the following code:
<ifModule mod_rewrite.c>
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\/$
RewriteRule ^(.*) /
</ifModule>
<IfModule mod_headers.c>
<FilesMatch "sw\.js$">
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>
</IfModule>
When I add that, the routes get directed to secured https, but the www is there when I type it in the url. How can I have the browser always redirect to not have www.?
The rediretion to another host should work better like that, note the hard wired target host name:
RewriteEngone on
RewriteCond %{HTTPS} off
RewriteRule ^/?(.*)$ https://example.com/$1 [R=301]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^/?(.*)$ https://example.com/$1 [R=301]
It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...
Place those rules before any internal rewriting rules (your example shows a general rewriting to ?/).
This implementation will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).
I have an AngularJS app hosted using Elastic Beanstalk and I'd like to remove the hashbangs (#!) from urls, but am having trouble using config files to make the necessary modifications to the Apache server.
I have enabled html5mode in my angular app and I currently have the following config file in my .ebextensions directory
files:
"/etc/httpd/conf.d/wsgirewrite.conf":
mode: "000644"
owner: root
group: root
content: |
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html
Everything works fine without the hashbangs until I reload the page and I get a 404 indicating that the rewrite rules aren't working.
If possible, I'd like to avoid any solutions that involve ssh, copying, and modifying one of the default configs as this will likely make maintenance a nightmare if AWS changes any defaults down the road
Hashbang is a fallback mechanism for older browsers, where HTML5 is not supported. Check illustration:
What you may be looking for is how to configure "pretty URLs" in AngularJS. Besides enabling HTML5 mode (which it seems you already did: $locationProvider.html5Mode(true)), you need to configure the <base href="/"> tag inside your <head>, specifying the base URL/target for all relative URLs in a document.
Note: the $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
By Angular's documentation, without #, the url looks much nicer, but it also requires server side rewrites. This is the httpd.conf example they have for Apache server:
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Since you are working with Beanstalk, you need to config httpd.conf via ebextensions. Two options available for Apache:
To override the Elastic Beanstalk default Apache configuration completely, include a configuration in your source bundle at .ebextensions/httpd/conf/httpd.conf.
To extend the Elastic Beanstalk default Apache configuration, add .conf configuration files to a folder named .ebextensions/httpd/conf.d in your application source bundle (e.g. .ebextensions/httpd/conf.d/port5000.conf).
I would recommend the extension option.
References:
https://scotch.io/tutorials/pretty-urls-in-angularjs-removing-the-hashtag
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-tomcat-proxy.html
https://docs.aws.amazon.com/pt_br/elasticbeanstalk/latest/dg/ebextensions.html
I'm trying to install LetsEncrypt with cakephp and I'm having some issues.Let me describe:
First I'm installing LetsEncrypt on a server with CentOS 6.
As mentioned on several websites it needs a python upgrade from 2.6 to 2.7 as LetsEncrypt needs Python 2.7. Which I did.
Then if I run ./letsencrypt-auto I get
"No installers are available on your OS yet; try running "letsencrypt-auto certonly" to get a cert you can install manually"
I understand that this is normal as there is no installer for CentOS 6.
So I run ./letsencrypt-auto certonly.A window appears.I have the choice between:
Place files in webroot directory
Automatically use a temporary webserver
So I press 1.Then I enter my domain name.And I see:
Enter a new webroot
I press ok and I see my root directory.I select /root
And then I have the following error:
Failed authorization procedure. www.example.com (http-01): urn:acme:error:unauthorized :: The client lacks sufficient
authorization :: Invalid response from
http://www.example.com/.well-known/acme-challenge/-CnpDIgxBB9EOH-BCssGOyiunFjnMlGLWhWw9roE4Ds:
"
500 Internal Server Error Inter"
IMPORTANT NOTES:
- The following errors were reported by the server:
Domain: www.example.com Type: unauthorized Detail: Invalid
response from http://www.example.com/.well-known
/acme-challenge/-CnpDIgxBB9EOH-BCssGOyiunFjnMlGLWhWw9roE4Ds:
"
500 Internal Server Error
Inter"
To fix these errors, please make sure that your domain name was
entered correctly and the DNS A record(s) for that domain
contain(s) the right IP address.
And here comes cakephp. As mentioned I'm using cakephp. And it seems that for this specific issue you need to modify htaccess files as mentioned here
I need to add "RewriteRule ^(\.well-known/.*)$ $1 [L]" as the first rewrite rule in the root htaccess and the app/.htaccess
Which I did.
root .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(\.well-known/.*)$ $1 [L]
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
AddDefaultCharset UTF-8
</IfModule>
app/.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(\.well-known/.*)$ $1 [L]
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
AddDefaultCharset UTF-8
</IfModule>
But I still have the same problem
Any idea what I did wrong?
Thanks a lot
Cake's webroot has an .htaccess with a RewriteCond %{REQUEST_FILENAME} !-d rule that means cake will not be called in for any request that matches an actual directory inside webroot.
So just place the .well-known directory and everything else that is needed inside the webroot directory, you should be able to access them fine without messing up with .htaccess.
PS. In some cases the file Let's encrypt requires is not served back as text, in which case you should enable the headers apache module (if not enabled already) and put the following rule in your apache or virtualhost config:
<IfModule mod_headers.c>
<LocationMatch "/.well-known/acme-challenge/*">
Header set Content-Type "text/plain"
</LocationMatch>
</IfModule>
I seriously can't understand what is going on here. I just uploaded my web app from localhost to new domain-name on Windows IIS Server. When I try to access the web app, CSS files and images are not loaded and I get the following error:
"CssController could not be found."
I don't understand why it is doing this.
Although I've written code like this in my default.ctp:
echo $this->html->css('generic');
CSS files are placed in:
app\webroot\css
I have searched on Google and have tried everything, I even uncommented the line:
Configure::write('App.baseUrl',env('SCRIPT_NAME')); in core.php
But I still cannot get this to work. Please help me to resolve this issue.
Double check that you have all the .htaccess files in place.
Also making sure /app/webroot/ has its .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
Your request is trying to get the css file from /css/ but i'm thinking you don't have the proper .htaccess files in place to route it to the webroot and not to a controller!
also check if mod_rewrite is enabled
Edit: and then I saw the IIS part, you need some IIS equivalent to mod_rewrite
In this article you find all the information required for successfully run CakePHP web applications under Microsoft IIS web server: http://bakery.cakephp.org/articles/filippo.toso/2008/01/29/cakephp-on-iis
Here is a related question about getting cake to work on IIS: CakePHP 2.2.2 not working on Windows IIS7