How to redirect // in Laravel 5.7? - php

Older version of laravel here, 5.7. I have a situation where I have a url like this http://127.0.0.1:8000//
I have a catch all of this
Route::get('{uri}', ['uses'=>'PageController#render'])->where('uri', '(.*)');
The URL that comes into the render method is ''.
I'm not quite sure the best way to take http://127.0.0.1:8000// and redirect that to http://127.0.0.1:8000.
.htaccess doesn't seem to let me redirect that either with
Redirect 301 // / or RewriteRule ^$ /? [L,R=301]
Is there any way to get around this?
thanks!

They are treated as the same resource in the browser. Anyway you can check the request URI on the server and redirect to the root path like this:
Route::get('/', function () {
// check the request URI
if($_SERVER['REQUEST_URI'] !== '/')
{
return redirect('/');
}
# The rest of the code
# ...
});

Related

Symfony Redirect

guys I'm new with Symfony and I have the follow question to see if this is possible.
Righ now I have an app that runs on Symfony that is located in www.domain.com/app and I want to if a user visits the URL redirect to another website (since a lot of users tries to brute force the login dashboard) but if I put the Symfony app login URL that is www.domain.com/app/dashboard/login the login dashboard appears.
I have to try to do something with .htaccess but with not luck.
Thanks
maybe something like
RewriteRule ^app$ "http://otherwebsite.example.com/$1" [R,L]
in your .htaccess ? The complete login URL will still work because this Rule only catches URLS ending with app
Actually your question is not so Symfony specific. It is more about Rewrite Rules.
Also, why not just answer with an error 404 if somebody accesses /app, (here with optional trailing slash) ?
RewriteRule ^app(\/?)$ - [L,R=404]
to redirect any request you can use return $this->redirect('http://stackoverflow.com');
You have a lot of soulion this one :
public function indexAction()
{
return $this->redirect('http://symfony.com/doc');
}
don't forget to check the documentation:
http://symfony.com/doc/2.8/controller.html#redirecting

Apache - Redirect All Traffic without ModRewrite

I'm trying to redirect all incoming requests to /index.php (except requests starting with ? like /?foo=bar)
ModRewrite could certainly solve this problem easily, but are there any other solutions?
For example I was thinking about creating a manual 404 page (in PHP) that would redirect to /index.php manually, but I'm not sure if/how this would work.
It would also be important to have the information from the original URI in index.php, e.g. when somebody is requesting domain.com/search-term then I need that information ("search-term") in index.php.
Interesting question. Even frameworks such as laravel will require a RewriteRule to push requests to index.php before doing any routing from within the framework itself.
I feel like to do a catch all as you are suggesting there would need to be some amount of Apache configuration changes.
your suggestion of redirecting the 404 page to index.php would work but the SEO implications id assume would be horrible. Any links to your site to any page other than index.php would give a 404 Not Found error in the HTTP headers (even though it shows index.php).
but.. with all that said, if you still want to do it that way, heres how you'd do it:
in .htaccess
ErrorDocument 404 /index.php
this will make your 404 not found page index.php
your redirect variables will be in the $_SERVER array and will be prefixed with REDIRECT_
print_r($_SERVER); from a redirect gives me (i removed any key value pairs without REDIRECT_ at the beginning):
Array
(
[REDIRECT_REQUEST_METHOD] => GET
[REDIRECT_STATUS] => 404
[REDIRECT_URL] => /blsah.html
)
so REDIRECT_URL would be what you would use to get "search-term" from domain.com/search-term
you can find a more complete list of the possible redirect variables here:
http://httpd.apache.org/docs/2.2/custom-error.html
You need to use some sort of routing component, such as those that exist in frameworks to handle redirect all routes. For example if you were using laravel 4 you could do something like this within the routes.php file:
Route::any('/', function(){
//Do Magic Stuff
});
Route::any('{all}', function($uri)
{
//Check query string here - redirect as necessary
if (stripos($_SERVER['QUERY_STRING'], '?') !== false)
//Redirect or do stuff depending on your use case
else
Redirect::to('/'); //Otherwise redirect to your homepage
})->where('all', '.*');
The all will match all routes and redirect them to the first route which would be your default. There are plenty of php frameworks out there that you could probably do this with or could even do it from scratch - this is just one framework that I find to be great to work with.
Credit to Jason Lewis: Get all routes, Laravel 4
Laravel Routing: http://laravel.com/docs/routing

Username as subdomain on laravel

I've set up a wildcard subdomain *.domain.com & i'm using the following .htaccess:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www\.
RewriteCond %{HTTP_HOST} (.*)\.domain\.com
RewriteRule .* index.php?username=%1 [L]
Everything works perfectly.
I want to implement this method in laravel. Mainly I want to have my user's profile displayed when you go to username.domain.com. Any ideas on achieving this?
This is easy. Firstly - do NOT change the .htaccess file from the default provided by Laravel. By default all requests to your domain will be routed to your index.php file which is exactly what we want.
Then in your routes.php file just use a 'before' filter, which filters all requests to your application before anything else is done.
Route::filter('before', function()
{
// Check if we asked for a user
$server = explode('.', Request::server('HTTP_HOST'));
if (count($server) == 3)
{
// We have 3 parts of the domain - therefore a subdomain was requested
// i.e. user.domain.com
// Check if user is valid and has access - i.e. is logged in
if (Auth::user()->username === $server[0])
{
// User is logged in, and has access to this subdomain
// DO WHATEVER YOU WANT HERE WITH THE USER PROFILE
echo "your username is ".$server[0];
}
else
{
// Username is invalid, or user does not have access to this subdomain
// SHOW ERROR OR WHATEVER YOU WANT
echo "error - you do not have access to here";
}
}
else
{
// Only 2 parts of domain was requested - therefore no subdomain was requested
// i.e. domain.com
// Do nothing here - will just route normally - but you could put logic here if you want
}
});
edit: if you have a country extension (i.e. domain.com.au or domain.com.eu) then you will want to change the count($server) to check for 4, not 3
Laravel 4 has this functionality out of the box:
Route::group(array('domain' => '{account}.myapp.com'), function() {
Route::get('user/{id}', function($account, $id) {
// ...
});
});
Source
While I can't say what the full solution would be in your case, I would start with the SERVER_NAME value from the request (PHP: $_SERVER['SERVER_NAME']) such as:
$username = str_replace('.domain.com', '', Request::server('SERVER_NAME'));
Make sure you additionally clean/sanitize the username, and from there you can lookup the user from the username. Something like:
$user = User::where('username', '=', $username)->first();
Somewhere in the routes file you could conditionally define a route if the SERVER_NAME isn't www.domain.com, or domain.com, though I'm sure others can come up with a much more eloquent way for this part...
ability add subdomains like subdomain *. domain.com should be switched by your hosting provider, in the .htaccess you can not configure support of subdomains

Allow optional trailing slash when using optional parameter

Given this path: /page(/:pageID), how can I allow the following variations:
/page and /page/ (even if the pageID part is missing.
/page/1 and /page/1/
Thank you.
You must define your route this way:
$app->get('/page(/:id/?)', function ($id = NULL) use ($app) {
; // your code
});
The answer provided by #inst would not work here (Slim 2.0.0 running on XAMPP): /page/ gives out a 404.
This works in all four cases though:
$app->get('/page(/)(:id/?)', function ($id = NULL) use ($app) {
echo 'success';
});
As stated in the documentation, optional segments may be unstable depending on the usage. For example, with the answer given by Fabien Snauwaert, and the following routes:
/:controller(/)(:action(/)(:overflow+/?))
/:controller(/)(:action(/:overflow+/?))
If not filled all the arguments, when obtain param values, these will be in a position to the right, resulting in action == controller and overflow == action.
To prevent this, a simple solution is to put the optional slash at the end of the route.
/:controller(/:action(/:overflow+))/?
/:controller(/:action(/:overflow+))(/)
And it is more readable, isn't it?
I can not comment on others answers, so I write here a detail concerning the Igor response.
One "problem" with this approach is that if the user tries to access a page that does not exist, and also do with a trailing slash, will be a 301 redirect to display a 404 page. Maybe a little weird.
I found this way to achive this with Apache mod_rewrite enabled. Snippet of .htaccess
RewriteEngine On
# remove trailing slash
RewriteCond %{HTTPS} off
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteRule ^(.+[^/])/$ https://%{HTTP_HOST}/$1 [R=301,L]
An example for Slim V3:
/[{param1:[0-9]+}[/[{param2:[0-9]+}[/]]]]
This will cover:
/
/1
/1/
/1/2
/1/2/

Redirect to a Rewritten URL

OK, so I'm rewriting some page URLs for a custom PHP cart.
I've got the following rules:
RewriteRule ^category/([0-9]+)/([a-z-]+)$ /store.php?cat=$1 [L]
RewriteRule ^product/([0-9]+)/([a-z-]+)$ /product.php?id=$1 [L]
These will allow me to use a url structure like example.com/product/23/product-slug.
That part is working alright. I'm wondering what options I have for the other direction; redirecting requests for the OLD url to the NEW url. So for example, when someone goes to /product.php?id=2 I want to redirect to /products/2/slug.
Any idea how to get this done?
I tried a simple redirect, but would not work:
Redirect 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
Redirect only takes a url prefix, not a regex (e.g. /store.php or /store)
You need to try RedirectMatch:
RedirectMatch 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
Also, is it supposed to start with a /? I'm not sure (your RewriteRule entries above start with no slash, for example)
I solved this a different way: with a modification to the store.php file.
I looked at output from print_r($_SERVER) after pinging both the normal and rewritten urls. I found that $_SERVER['SCRIPT_URL'] contains "/store.php" when the normal url is hit and it contains my rewritten path when the rewritten url is hit.
This means I can do a simple test and redirect appropriately:
if ($_SERVER['SCRIPT_URL'] == "/store.php") {
// run some code that will generate the url
$rewrittenURL = generateURL();
// then add:
header("HTTP/1.0 301 Moved Permanently"); // tell spiders this is permanent
header("Location: $rewrittenURL");
}

Categories