url routing throws 400 Bad Request error in CodeIgniter 4 - .htaccess

After being helped by other users’ questions uncountable times, I finally have to ask my first question.
What I’m trying to do:
Running a CodeIgniter project (ver. 4.2.8) on a live server.
Problem:
The URL routing is not working (400 Bad Request error).
It’s a fresh installation, so there are no pages other than the default CodeIgniter homepage (the one that says “Welcome to CodeIgniter”).
The welcome page displays correctly when I access it like this:
www.example.com
www.example.com/index.php
I get the Bad Request error when I try:
www.example.com/home
Here's what I've done:
Folder structure on server:
root
|
+ | dir public_html
| |
+ | dir www.example.com //web root, this is where I put the files that were in the CI public folder
+ | dir exampleCI4 //here I put all the other CI files and folders app, vendor, writable...
I have adjusted following files:
exampleCI4/app/Config/App.php
public $baseURL = 'http://www.example.com'
www.example.com/index.php
// Load our paths config file
// This is the line that might need to be changed, depending on your folder structure.
require FCPATH . '../exampleCI4/app/Config/Paths.php';
// ^^^ Change this line if you move your application folder
At first I always got a 500 Internal Server error. After hours of searching for solutions I came across this post:
CodeIgniter4 htaccess won't work with Options All -Indexes
That indeed did solve the 500 Internal Server error, and the welcome page is displaying. I also confirmed with my hosting provider and it turns out that they don't allow Options All and FollowSymlinks.
I'm pretty sure there is something in the htaccess file that needs to be adjusted but I don't know what.
Here's the complete htaccess file:
public_html/www.example.com/.htaccess
#Disable directory browsing
Options -Indexes
# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------
# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
# Options +FollowSymlinks
Options +SymLinksIfOwnerMatch
RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
# RewriteBase /
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ ../index.php/$1 [L,NC,QSA]
# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>
# Disable server signature start
ServerSignature Off
# Disable server signature end
If somebody could tell me what needs to be changed in order for it to work, that would be awesome.

Got it running.
Turned out I had forgotten to make the necessary adjustments in the spark file.
Changed this part here:
/*
*---------------------------------------------------------------
* BOOTSTRAP THE APPLICATION
*---------------------------------------------------------------
* This process sets up the path constants, loads and registers
* our autoloader, along with Composer's, loads our constants
* and fires up an environment-specific bootstrapping.
*/
// Load our paths config file
// This is the line that might need to be changed, depending on your folder structure.
require FCPATH . 'app/Config/Paths.php';
// ^^^ Change this line if you move your application folder

Can you try this in the config file? Set the base URL like:
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". #$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;

Related

Rewrite .htaccess symfony 3.4 for main page

I have the current htaccess file.
When I go to my main website http://mywebsite.com I receive this error that says Forbidden
You don't have permission to access / on this server.
However, by adding web at the end as http://mywebsite.com/web, I am able to access to the website.
Is it possible to rewrite the .htaccess file to include that redirection so I won't need to add web every time?
Edit: My app is located in /www/mywebsite
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the app.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by Apache
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/app.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite all other queries to the front controller.
RewriteRule ^ %{ENV:BASE}/app.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 302 ^/$ /app.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>

Set up symfony4 URI with ONLY .htaccess

I am launching a symfony website on a server that can't be configured at all. So I can't touch the apache conf and all, I only have access to the drop repository.
So I need to use ONLY htaccess to :
point to the "public/index.php" file
Remove the "public" part from the url
I now have succeded the 1rst part with this in my lowest level .htaccess:
DirectoryIndex public/index.php public/index.html
My second .htaccess is the basic one:
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
# to the front controller "/index.php" but be rewritten to "/index.php/index".
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the index.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by Apache
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/index.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite all other queries to the front controller.
RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
<IfModule mod_alias.c>
# When mod_rewrite is not available, we instruct a temporary redirect of
# the start page to the front controller explicitly so that the website
# and the generated links can still be used.
RedirectMatch 307 ^/$ /index.php/
# RedirectTemp cannot be used instead
</IfModule>
</IfModule>
How can I do the second part ?
I believe you are solving things the other way around. The proper solution is described here https://medium.com/#runawaycoin/deploying-symfony-4-application-to-shared-hosting-with-just-ftp-access-e65d2c5e0e3d
Upload the following folders (and contents) from your application to a new folder in your root of your FTP server named symfony:
bin
config
src
templates
translations
vendor
Note: Only upload the bin folder if you want to run the console, maybe via a cron job, also best to rename console to console.php
Also create the var folder but dont upload its contents.
And upload your composer.json file to this symfony folder — this is needed to help symfony find its application files.
So you should have this on your server:
\symfony
bin
config
src
templates
translations
vendor
composer.json
\public_html
index.php
.htaccess
bundles
build
Dont forget that you will need to modify index.php
Before your application will work you need to modify your index.php file and set your env vars.
First edit your index.php (locally inside your public folder, on the server will be inside your public_html folder).
Edit this line:
require __DIR__.’/../vendor/autoload.php’;
To:
require __DIR__.’/../symfony/vendor/autoload.php’;

htaccess rewrite a get parameter

I have already the Typo3 Flow .htaccess
#
# TYPO3 Flow context setting
#
# You can specify a default context by activating this option:
# SetEnv FLOW_CONTEXT Production
# If the root path is not the parent of the Web directory,
# TYPO3 Flow's root path must be specified manually:
# SetEnv FLOW_ROOTPATH /var/www/myapp/
#
# mod_rewrite configuration
#
<IfModule mod_rewrite.c>
# Enable URL rewriting
RewriteEngine On
# Set flag so we know URL rewriting is available
SetEnv FLOW_REWRITEURLS 1
# You will have to change the path in the following option if you
# experience problems while your installation is located in a subdirectory
# of the website root.
RewriteBase /
# Stop rewrite processing no matter if a package resource, robots.txt etc. exists or not
RewriteRule ^(_Resources/Packages/|robots\.txt|favicon\.ico) - [L]
# Stop rewrite process if the path points to a static file anyway
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]
# Perform rewriting of persistent private resources
RewriteRule ^(_Resources/Persistent/[a-zA-Z0-9]+/(.+/)?[a-f0-9]{40})/.+(\..+) $1$3 [L]
# Perform rewriting of persistent resource files
RewriteRule ^(_Resources/Persistent/.{40})/.+(\..+) $1$2 [L]
# Make sure that not existing resources don't execute TYPO3 Flow
RewriteRule ^_Resources/.* - [L]
# Continue only if the file/symlink/directory does not exist
RewriteRule (.*) index.php
</IfModule>
<IfModule mod_negotiation.c>
# prevents Apache's automatic file negotiation, it breaks resource URLs
Options -MultiViews
</IfModule>
<IfModule mod_setenvif.c>
# Redirect authorization header when PHP is running as CGI
SetEnvIfNoCase Authorization "Basic ([a-zA-Z0-9\+/=]+)" REMOTE_AUTHORIZATION=$0
</IfModule>
ErrorDocument 500 "<h1>Application Error</h1><p>The TYPO3 Flow application could not be launched.</p>"
So i think this is the standard flow htaccess.
Is there a possibility to define own rules?
My htaccess skills are quite bad. What do i have to edit do replace a GET parameter
show?path=
My Domain looks like
http://domain.com/show?path=/test/test2
It should look like
http://domain.com/show/test/test2
thanks in advance, regards
Yes, you can extend .htaccess and if you have mod_proxy enabled adding this line should be enough (check what [P] flag does)
# Add this line
RewriteRule ^show/(.*)$ /show?path=/$1 [P]
# Continue only if the file/symlink/directory does not exist
RewriteRule (.*) index.php
But you should handle this kind of stuff using Routing - then you will have uri builder and rewriting handled by framework.
If your path is just string argument in showAction, ten adding to My/Package/Configuration/Routes.yaml (and setting subroutes in main Configuration/Routes.yaml above Flow subroutes)
-
name: 'show'
uriPattern: 'show/{path}'
defaults:
'#package': 'My.Package'
'#controller': 'Standard'
'#action': 'show'
'#format': 'html'
appendExceedingArguments: true
If it's property of object you have example in link above.
The only problem is that / in argument (like '/test/test2') won't work with route above.. To handle arguments containing / you might need to create your own Route Part Handler.

Unable to host codeigniter project in a web server

I have created a web project in codeigniter. In my localhost (windows 7) I could run the project with no errors. But when I try to host my project in my university subdomain (the administrator gave me a subdomain to host my files myproject.university.edu.bt). I uploaded all my files via filezilla. When I try to access my page, which starts with a login page. It displays the login button without any of the styles that I have coded for the site. When clicking the login button instead of displaying the next page it gives me an error The requested URL /sasec/login/user_login was not found on this server. Can anybody tell me what I should do to view/display my pages correctly! Here is my .htaccess file. The university server is running on linux
<IfModule mod_rewrite.c>
# Turn on URL rewriting
RewriteEngine On
# If your website begins from a folder e.g localhost/my_project then
# you have to change it to: RewriteBase /my_project/
# If your site begins from the root e.g. example.local/ then
# let it as it is
RewriteBase /
# Protect application and system files from being viewed when the index.php is missing
RewriteCond $1 ^(application|system|private|logs)
# Rewrite to index.php/access_denied/URL
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]
# Allow these directories and files to be displayed directly:
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets|css|js|images)
# No rewriting
RewriteRule ^(.*)$ - [PT,L]
# Rewrite to index.php/URL
RewriteRule ^(.*)$ index.php/$1 [PT,L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin
ErrorDocument 404 /index.php
</IfModule>
Go to config/routs.php
Change this
$route['default_controller'] = '';//give your default controller name
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
in addition
Path - config/config.php
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
You will have to probably change something with
RewriteBase /
in your htaccess file, link given below will give you more idea.
https://www.daniweb.com/web-development/php/threads/435526/codeigniter-remove-index-php-while-working-on-virtual-host-on-xampp
Thanks
Amit

Please assist in mod rewriting application/views directory to "views" in Kohana

Due to the way I have chosen to template my website, I am needing to rewrite "application/views" to "views". I have chosen to do this (1) to shorten the URL I'll be using in linking stylesheets etc as well as covering up the structure of my file system.
Currently, if I remove the rewrite rule I can access the media files directly at application/views/template/file.css. When I enable the rewrite rule I am redirected to views/template/file.css but Kohana returns: Kohana_HTTP_Exception [ 404 ]: Unable to find a route to match the URI: template/u_crossbrowser/css/bootstrap.css
I imagine I could dig into the script and make a condition stating that if url is calling views dir, do not try to control the routing. But I imagine there is a better solution.
My .htaccess file:
RewriteEngine on
# Installation directory
RewriteBase /
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
#We needed direct file access for our media files (css, js, images) but the rewrite below was breaking it. So, we replaced it with rule 2 below.
# Protect application and system files from being viewed
# RewriteRule ^(?:application|modules|system)\b - [F,L]
# Rule 2: Disable directory listings
IndexIgnore *
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php [PT]
RewriteCond %{THE_REQUEST} ^GET\ /application/views/
RewriteRule ^application/views/(.*) /views/$1 [L,R=301]
You have two problems here:
Your rule to rewrite /application/views/... to /views/... is after the rule that rewrites everything to index.php. You need to put the more-specific rewrite before the more-general rewrite to prevent the more-general one from stopping the processing.
Your rewrite rule is incomplete. You have a rule so that requests to /application/views/... get rewritten as if the files are actually at /views/.... However, since you are still actually storing the files in the application/views/ folder, you are missing the rule that lets you access them as if they are at /views/....
Here is one way you could make the rewrite rules in order to get it to work. (I left out the rule that redirects /application/views/... to /views/... because I don't see why you need it - just make /application inaccessible and only use /views/... and then it won't matter anyway.)
RewriteEngine on
# Installation directory
RewriteBase /
# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>
# Pretend that views are one directory above where they actually are
RewriteRule ^views/(.*) application/views/$1 [L]
# Protect application and system files from being viewed,
# UNLESS we are redirecting to them from another rule
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(?:application|modules|system)\b - [F,L]
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php [PT]
(thanks to #CDuv's answer to mod_rewrite: allow redirect but prevent direct access for the ENV:REDIRECT_STATUS trick.)
In truth, you may find that it makes more sense to create a route to this content. This is because it allows you to move the application, modules, and system directories out of the web root. One benefit of doing this is that you can share the modules and system between multiple Kohana applications if you ever develop another one. Another is that it means you don't need to rely on htaccess to protect access to these directories.
Here is a simple method you can use to serve these files, based on the Kohana Userguide module.
Add this route in bootstrap.php:
// Static file serving (CSS, JS, images) - ADD MORE EXTENSIONS IF NEEDED
Route::set('media', 'views(/<file>)', array('file' => '.+\.(css|js|jpg|png)'))
->defaults(array(
'controller' => 'media',
'action' => 'media',
'file' => NULL,
));
Add a controller Controller_Media:
class Controller_Media extends Controller
{
public function action_media()
{
// Get the file path from the request
$file = $this->request->param('file');
// Find the file extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
// Remove the extension from the filename
$file = substr($file, 0, -(strlen($ext) + 1));
if ($file = Kohana::find_file('views', $file, $ext))
{
// Check if the browser sent an "if-none-match: <etag>" header, and tell if the file hasn't changed
$this->check_cache(sha1($this->request->uri()).filemtime($file));
// Send the file content as the response
$this->response->body(file_get_contents($file));
// Set the proper headers to allow caching
$this->response->headers('content-type', File::mime_by_ext($ext));
$this->response->headers('last-modified', date('r', filemtime($file)));
}
else
{
// Return a 404 status
$this->response->status(404);
}
}
}

Resources