I have a very simple Slim app that works fine on my Ubuntu machine but I get an error 500 when I deploy it to a Hostgator shared account using a subdomain.
I suspect the problem lies in my .htaccess file.
The structure of my files is:
project/
├──api/
│ ├── .htaccess
│ ├── services.php
├──src/
├──vendor/
My Slim app (services.php):
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require_once '../src/vendor/autoload.php';
$c = new \Slim\Container();
$c['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'text/html')
->write('Invalid endpoint');
};
};
$app = new \Slim\App($c);
$app->post('/myEndpoint', function (Request $request, Response $response, array $args) {
if($request->getHeader("key") != null && $request->getHeader("key")[0] == "123456789="){
$reqdata = $request->getParsedBody();
$data = $reqdata['data'];
return json_encode('{"data":'.$data.',"response":"OK","errorcode":"0"}');
} else {
return '{"data":"","response":"Access denied","errorcode":"9999"}';
}
});
$app->run();
My .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . services.php [QSA,L]
</IfModule>
# Use PHP71 as default
AddHandler application/x-httpd-php71 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php71/lib
</IfModule>
I created a subdomain (api.mydomain.com) with project/api/ as document root.
When I make a POST request in my local installation to
127.0.0.1/api/services.php/myEndpoint
works as expected and returns the data. However, when I make the same request to my Hostgator subdomain:
api.mydomain.com/services.php/myEndpoint
I get the error 500.
Note that if I add a simple test.php file to my api/ directory that only prints something, e.g.
<?php
echo "OK"
?>
and I go to api.mydomain.com/test.php, it works fine and prints the string.
What do I need to change or add in my .htaccess for my slim app to work?
I solved it by doing two things:
I moved my project folder to public_html, created again the subdomain and pointed it to the project directory.
I updated my .htaccess file IfModule mod_rewrite.c section. It now looks like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ services.php [QSA,L]
</IfModule>
The difference with the previous one is I added this line:
RewriteBase /
And this one:
RewriteRule . services.php [QSA,L]
updated to this:
RewriteRule ^ services.php [QSA,L]
I got the .htaccess fixes here:
https://discourse.slimframework.com/t/deploy-slim-project-to-hostgator-using-subdomain/3187/7
Related
I created a blank new project on Angular 4 (with angular-cli) in order to try to use it with PHP Routes, I'm using Phroute Fast route.
Before trying this I used to call the whole file with a param to call a specific function, like this:
angular service
apiGet(): any {
return this._http.get('api/server/user.php?action=getUser');
}
I tried to install the Phroute but it didn't worked, when I try to call it like the code bellow, I get the following error:
apiGet(): any {
return this._http.get('api/user');
}
GET http://localhost/api/index.php net::ERR_TOO_MANY_REDIRECTS
Folder structure:
api/
server/ (used to call files with extensions)
vendor/
index.php
index.html
bundle.js
[..other angular files..]
index.php
require 'vendor/autoload.php';
function processInput($uri) {
$uri = implode('/', array_slice(
explode('/', $_SERVER['REQUEST_URI']), 3
));
return $uri;
}
function processOutput($response){
echo json_encode($response);
}
$router = new Phroute\RouteCollector(new Phroute\RouteParser);
$router->get('user', function(){
return 'Hello, PHRoute!';
});
$dispatcher = new Phroute\Dispatcher(router);
try {
$response = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], processInput($_SERVER['REQUEST_URI']));
} catch (Phroute\Exception\HttpRouteNotFoundException $e) {
var_dump($e);
die();
} catch (Phroute\Exception\HttpMethodNotAllowedException $e) {
var_dump($e);
die();
}
processOutput($response);
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} api
RewriteRule ^ /api/index.php [L,R]
# This code needs to be used in order to enable refresh
# and redirects on the Angular routes
RewriteBase /
RewriteRule ^index.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Note: Keep in mind I'm very new to this PHP route concept, so any other advice is also welcome!
So I'd like to know how do I properly configure this to make it work? I didn't found any tutorial on this topic, so it was very confusing to me.
This piece of code was from an example at heroku. But except the route /, anything else I add does not work. It shows 404:
The requested URL /e was not found on this server.
$app->match('/', function(Symfony\Component\HttpFoundation\Request $request) use ($app) {
return $app['twig']->render('index.twig');
});
$app->match("/dump", function(Symfony\Component\HttpFoundation\Request $request) use ($app) {
return new Response('Thank you for your feedback!', 201);
})->bind("dump");
$app->get("/t", function() use ($app) {
return new Response('Thank you for your feedback!', 201);
})->bind("t");
$app->get("/d", function() {
return new Response('Thank you for your feedback!', 201);
})->bind("d");
$app->get("/e", function() {
return new Response('Thank you for your feedback!', 201);
});
$app->run();
Edit 1
I deployed it directly on heroku server (heroku auto build on each push to master branch)
Edit 2
my workspace:
bin\worker.php
www\index.php <== the snippet is from this file
www\list.php
apache_app.conf
app.php <== basic init, return Silex\Application $app
Procfile
The content of apache_app.conf is copied from this link.
RewriteEngine On
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .? - [L]
RewriteRule .? %{ENV:BASE}/app.php [L]
I figured that I need to change the apache config somehow, but I don't understand htaccess syntax.
For apache2, you can add a .htaccess file within "/web"
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
#RewriteBase /path/to/app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
and set your Procfile as:
web: vendor/bin/heroku-php-apache2 web/
For nginx, create a nginx conf file with content:
location / {
# try to serve file directly, fallback to rewrite
try_files $uri #rewriteapp;
}
location #rewriteapp {
# rewrite all to index.php
rewrite ^(.*)$ /index.php/$1 last;
}
location ~ ^/(index|index_dev)\.php(/|$) {
try_files #heroku-fcgi #heroku-fcgi;
internal;
}
and set Procfile as:
web: vendor/bin/heroku-php-nginx -C server_conf/nginx.conf web/
It's very simple, just install apache :
composer require apache-pack
I had the same issue, and it stumped me for weeks... to the point where I just started using / as my only route and adding other capability through passed-in variables. Drove me up the wall.
I finally had the need to fix it for real, and after a few hours found this post:
https://laracasts.com/discuss/channels/laravel/laravel-v5415-on-heroku-all-routes-but-not-working
TL/DR; I had duplicated a (correctly working) heroku repo to create my new one, and somewhere along the way my web/.htaccess file got deleted. I replaced it, and everything works like a charm.
For me the provided test also worked well (I'm using PHP): if eaxmple.com/ROUTE doesn't work, but example.com/index.php/ROUTE does work... you have an .htaccess problem.
Also, for reference, here's my entire .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Hopefully this saves someone some searching...
I need some help to use Slim Framework. Indeed, I'm a beginner in PHP and I would like to migrate my API using Slim Framework in order to have a clean code. I successed to run Slim Hello Word app on my WAMP server locally, but when I deploy it on my OVH server shared, I have a blank page on route [root]/myproject/hello/test.
The question has already asked but the problem was not exactly the same.
For information I had a 500 internal error locally which was resolved when I've activated rewrite_module on my WAMP server.
I have a SSH access to OVH server but composer is not installed. It seems that mod_rewrite is enabled. WAMP and OVH server use PHP 5.5
This is my folder directory:
Project/
src/
public/
.htaccess
index.php
vendor/
autoload.php
slim/
slim/
Slim/
App.php
...
composer.json
composer.lock
This is my .htaccess file
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
And my index.php
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../vendor/autoload.php';
$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
$name = $request->getAttribute('name');
$response->getBody()->write("Hello, $name");
return $response;
});
$app->run();
Any ideas to resolve it?
Thanks.
try to use this .htaccess config
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
#RewriteBase /path/to/app
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
Also install monolog https://github.com/Flynsarmy/Slim-Monolog
MVC uploaded on cloud9, but when the auto-load class located in lib/init.php is not working. The .htaccess in the project folder or webroot folder files are not properly configured.
When I visit my project link https://my-mvc-hunteelar.c9users.io/ it gives this exception :
Failed to load class: Config' in /home/ubuntu/workspace/lib/init.php on line 21
I have 2 .htaccess files. The first .htaccess code in the main project folder is:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
The second .htaccess file located in the webroot folder which is supposed to be the public folder of my MVC:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [PT,L]
</IfModule>
The init.php code which contains the __autoload function.
require_once (ROOT.DS.'config'.DS.'config.php');
function __autoload($class_name){
$lib_path = ROOT.DS.'lib'.DS.strtolower($class_name).'class.php';
$controllers_path = ROOT.DS.'controllers'.DS.str_replace('controller', '', strtolower($class_name)).'class.php';
$models_path = ROOT.DS.'models'.DS.strtolower($class_name).'class.php';
if(file_exists($lib_path)){
require ($lib_path);
}
elseif (file_exists($controllers_path)){
require_once ($controllers_path);
}
elseif (file_exists($models_path)){
require_once ($models_path);
}
else{
throw new Exception('Failed to load class : '.$class_name);
}
}
Here is my code uploaded on cloud9 https://ide.c9.io/hunteelar/my-mvc
I think you already solved this. But the problem is with the initialization of your code.
$controllers_path = ROOT.DS.'controllers'.DS.str_replace('controller', '', strtolower($class_name)).'class.php';
should actually be:
$controllers_path = ROOT.DS.'controllers'.DS.str_replace('controller', '', strtolower($class_name)).'.controller.php';
Also
$models_path = ROOT.DS.'models'.DS.strtolower($class_name).'class.php';
Should be
$model_path = ROOT.DS.'models'.DS.strtolower($class_name).'.php';
In case it may help someone else.
I have a Laravel project
My domain is domain.com.tw
and the URL will be domain.com.tw/public,
and the page could be showed.
I want to remove the public in URL,
so I write RewriteRule in .htaccess with:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
but it did not work for me
I had look at these also, but still failed
Apache Mod Rewrite For Laravel
Laravel 4.2 rewrite URL - remove public
could someone tell me the solution? thanks!!
Create a folder on root with named “whatever”(you can give any name).
Move all files except public folder in the “whatever” folder.
Move all the files of public to root directory and remove blank public folder.
so directory structure will be:
whatever– which have all root files except public folder
all files of public folder.
Now time to change some paths
in paths.php change the following code
'public' => __DIR__.'/../public', into 'public' => __DIR__.'/../../',
open index.php (on root) and find below code
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/start.php';
change this to
require __DIR__.'/local/bootstrap/autoload.php';
$app = require_once __DIR__.'/local/bootstrap/start.php';
Hope this helps or at least give you some idea