Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$"> Order Allow,Deny Deny from all </FilesMatch>Loaded with some common extensions, add more as you need.ShareFollowansweredMay 18, 2010 at 18:43Chris LawlorChris Lawlor47.9k1111 gold badges4949 silver badges6969 bronze badgesAdd a comment|
Its been a long time since I've needed to crack open an .htaccess file...What is the simplest way to 40x prevent access to a specific file extension through out the entire site?
How to hide certain file type using apache .htaccess?
If I understand your question correctly, you can just add the[QSA](query string append) flagto the end of yourRewriteRuleRewriteRule ^([^/\.]+)/?$ page.php?page=$1 [L,QSA]This will process your request as you've already done, and add any further querystring params onto the end.ShareFolloweditedOct 14, 2015 at 13:11answeredMay 18, 2011 at 16:53Michael BerkowskiMichael Berkowski269k4646 gold badges445445 silver badges391391 bronze badges0Add a comment|
Currently I use:RewriteRule ^([^/\.]+)/?$ page.php?page=$1 [L]Which is good for when passing one querystring through.But is there a way just to pass all querystrings through? i.e. One page request might be:domain.com/contact?course=23and another may be:domain.com/contact?workshop=41So I need to know what the query string name is, but only ever one will be passed in at a time
.htaccess rewrite pass all query strings through
I had a similar problem, although was using $routeProvider in a SPA application. What I did was to enforce a redirect inside the controller:var forceSSL = function () { if ($location.protocol() !== 'https') { $window.location.href = $location.absUrl().replace('http', 'https'); } }; forceSSL();This though does reload all resources. However, this happens only once when switching to SSL mode.Note, the function is actually in a service so can be called from anywhere.I hope this helps.ShareFolloweditedMay 6, 2015 at 17:40Ryan Shea4,27244 gold badges3232 silver badges3232 bronze badgesansweredApr 14, 2014 at 4:51Andrej GroblerAndrej Grobler54466 silver badges55 bronze badges4We ended up implementing the whole site with SSL and used rewrite rules in htaccess but this would have worked! thanks!–Matt Foxx DuncanApr 14, 2014 at 18:536replace('http', 'https')- I would advise to use with caution, since there might be multiple occurrences of 'http' string in the URL.–s.ermakovichMar 31, 2015 at 21:247Actually in this particular case, replace will only happens for the first occurence of the 'http'. To happen globally, one way of doing it is $location.absUrl().replace(/http/g, 'https');–PinnyMay 5, 2015 at 21:11Great work! Just made a couple of tiny syntax fixes.–Ryan SheaMay 6, 2015 at 17:41Add a comment|
In our application we have a payment page that we want to use SSL on because we are handling credit card information. We've already put in place rewrite rules for apache to redirect a request to the specific page to HTTPS -- which takes care of any direct requests to the payment page (http://oursite.com/pay).However most navigation in our site is done via relative urls andstatesusingui-routerin angularjs and we have found that apache does not catch these requests and so serves the page without SSL.EX If a user clicks a link withui-sref='pay'ui-routerloads the template and refreshes the state -- at no point is a request made to the server for a new uri so apache can't redirect to httpsIs there a way to force ui-router(or angular in general) to force a state to use HTTPS without having to change all links to reload the entire site?Of course this may also be a shortcoming in our rewrite rules...Here's what we have so farRewriteEngine on RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} /pay RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^ index.html [L]The second set of rules is to enforce html5mode for our app.RewriteCond %{REQUEST_FILENAME} !-fis in place so that angular can fetch the payment template for the state without needing SSL. Is this okay?
Forcing a specific page to use HTTPS with angularjs
You can use these 2 lines at the top of your .htaccess:DirectoryIndex index.html ErrorDocument 404 http://domain.com/DirectoryIndexwill makehttp://domain.com/loadhttp://domain.com/index.htmlby default and use ofhttp://inErrorDocumentwill make it redirect to new URL.ShareFollowansweredOct 21, 2014 at 18:27anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges51or just: ErrorDocument 404 /–panticzFeb 25, 2017 at 11:421ErrorDocument 404 /will not change URL in browser–anubhavaFeb 25, 2017 at 12:001for me adding ErrorDocument was enough.–BrunoMartinsProJul 15, 2019 at 10:16Any insight in whether this is a good practice? Is it not more appropriate (and perhaps SEO abiding?) to have beautiful error pages with navigation to possible important entry points of the website?–s3cApr 7, 2021 at 13:04@s3c: This question was not about SEO. There can be some internal websites that are not open to public.–anubhavaApr 7, 2021 at 13:36Add a comment|
I changed a bulky, complex website into a small one-page website, so users need to be redirected from 404s to index.html.I put this in.htaccess:ErrorDocument 404 /index.htmlIf you typemydomain.com/lalalalala, this redirects to the home page content (mydomain.com/index.html), but the URL bar still saysmydomain.com/lalalalala.How do I redirect 404s toindex.htmland rewrite the URL tomydomain.com?EDIT:I'm using Bluehost.
How do I redirect 404's to index.html and rewrite the URL to the home page URL?
$1is the first captured group from your regular expression; that is, the contents between(and). If you had a second set of parentheses in your regex,$2would contain the contents of those parens. Here is an example:RewriteRule ([a-z0-9/-]+)-([a-z]+).html$ $1-$2.php [NC,L,QSA]Say a user navigates tohello-there.html. They would be servedhello-there.php. In your substitution string,$1contains the contents of the first set of parens (hello), while$2contains the contents of the second set (there). There will always be exactly as many "dollar" values available in your substitution string as there are sets of capturing parentheses in your regex.If you have nested parens, say,(([a-z]+)-[a-z]+),$1always refers to theoutermostcapture (in this case the whole regex),$2is the firstnestedset, and so on.ShareFolloweditedNov 15, 2019 at 9:51Jean-François Fabre♦138k2323 gold badges163163 silver badges226226 bronze badgesansweredJul 23, 2014 at 22:28user428517user4285174,16311 gold badge2222 silver badges3939 bronze badges14As a minor point here, since there is noRflag, this won't really "redirect" to that page; the rewrite will happen entirely internally. It is more accurate to say that a user navigating tohello-there.htmlwillbe servedhello-there.php; they will have no way of knowing that's what happened.–IMSoPJul 23, 2014 at 23:13Add a comment|
I am trying to understand the meaning of this line in the .htaccess fileRewriteRule ([a-z0-9/-]+).html $1.php [NC,L,QSA]basically what does $1.php ? what file in the serverif we have home.html where this gonna redirect to? home.php?
what does $1 in .htaccess file mean?
You'd use, in a.htaccessfile in theassets/directory:Satisfy Any Order Allow,Deny Allow from allSee the examples here:http://httpd.apache.org/docs/2.2/mod/core.html#requireShareFollowansweredMar 25, 2012 at 6:21David WoleverDavid Wolever151k9292 gold badges356356 silver badges505505 bronze badges13Ah I was stuck in a single .htaccess mindset. This worked perfectly. Thank you!–ShealanMar 27, 2012 at 22:04Add a comment|
I need to password protect a website with a username/password but need to keep the "/assets" folder accessible as files like images/css are being embedded on other sites.I have this for the protection:Order Allow,Deny AuthType Basic AuthName "Password" AuthUserFile /var/www/.htpasswd Require valid-user Satisfy AnyHow can I specify to protect everything bar the /assets folder?
Exclude folder from htpasswd
It is best handled with arobots.txtfile, for just bots that respect the file.To block the whole site add this torobots.txtin the root directory of your site:User-agent: * Disallow: /To limit access to your site for everyone else,.htaccessis better, but you would need to define access rules, by IP address for example.Below are the.htaccessrules to restrict everyone except your people from your company IP:Order allow,deny # Enter your companies IP address here Allow from 255.1.1.1 Deny from allShareFolloweditedFeb 10, 2017 at 1:20nyedidikeke7,25888 gold badges4444 silver badges6060 bronze badgesansweredFeb 1, 2012 at 20:36Ulrich PalhaUlrich Palha9,43933 gold badges2626 silver badges3131 bronze badges3Thanks for that, the robots.txt info is really helpful, I would love to only allow just the company ip range but the app is going to be used by reps on the road so their ip's can change all the time, otherwise I would certainly do that. Thanks :-)–Iain SimpsonFeb 1, 2012 at 20:44Is there way to block bad bots too, e.g by identifying them as being bots and not users and blocking them, as there is no reason anything other than a human should be accessing the website.–Iain SimpsonFeb 1, 2012 at 20:49@IainSimpson You could try to denybotsbased on userAgent, but it would be easy to spoof and its very likely that bad bots would not identify themselves as bots to begin with...–Ulrich PalhaFeb 1, 2012 at 21:07Add a comment|
I want to stop search engines from crawling my whole website.I have a web application for members of a company to use. This is hosted on a web server so that the employees of the company can access it. No one else (the public) would need it or find it useful.So I want to add another layer of security (In Theory) to try and prevent unauthorized access by totally removing access to it by all search engine bots/crawlers. Having Google index our site to make it searchable is pointless from the business perspective and just adds another way for a hacker to find the website in the first place to try and hack it.I know in therobots.txtyou can tell search engines not to crawl certain directories.Is it possible to tell bots not to crawl the whole site without having to list all the directories not to crawl?Is this best done withrobots.txtor is it better done by .htaccess or other?
How to stop search engines from crawling the whole website?
To allow execution of rewrite rules from parent .htaccess (htaccess from parent folder), you need to explicitly allow it (Apache will treat rewrite rules in current .htaccess as the only one that need to be executed, as long as rewritten URL remains in the same subfolder).You need to add this line to your .htaccess in sub-folder:RewriteOptions inheritApache manual:http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteoptionsShareFollowansweredSep 7, 2011 at 21:03LazyOneLazyOne162k4646 gold badges401401 silver badges404404 bronze badges113You could also putRewriteOptions InheritDownin parent htaccess if you want all child htaccess to inherit them.–GudradainNov 27, 2018 at 21:52Add a comment|
been searching for 2 days and can't quite get the right solution due to my lack of understanding of mod_rewrite and time constraints on this project so hoping someone can help.The aimTo rewrite all requests to the root index.php if the client doesn't have the correct cookie. If the client has the correct cookie allow them to browse as they wish.The problemThe htaccess in my subdirectory is taking precendence over my root htaccess, so requests such as www.mydomain.com/subdir/index.php arn't getting redirected.My root .htaccessOptions FollowSymLinks RewriteEngine On RewriteBase / RewriteCond %{HTTP_COOKIE} !^.*pass.*$ RewriteCond %{REQUEST_URI} !^/index.php$ RewriteRule ^(.*)$ http://www.mydomain.com/index.php?url=$0 [NC]My subdir htaccessRewriteEngine On RewriteBase / RewriteCond $1 !\.(gif|jpe?g|png)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L]Additional infoIdeally I'm trying to create a password protected area, so all requests are routed to index.php where a password can be entered and when verified a cookie is created, allowing free browsing of contents and sub directories. So if there is a better way to accomplish this then please let me know, and I havn't gone for .htpasswd since I need custom login, error and splash pages.Also, the subdir .htaccess is an ExpressionEngine URL handler.Thanks.
.htaccess in subdirectory 'overriding' parent htaccess
So you just need to ignorehttp://yourdomain.com/market-reports(in addition to files/directories?). You should be fine with:RewriteCond %{REQUEST_URI} !^/market-reports/?$This will (not) match "http://yourdomain.com/market-reports" as well as "http://yourdomain.com/market-reports/" as the question mark "?", in the Perl Compatible Regular Expression vocabulary that mod_rewrite uses, makes the match optional (a wildcard) before the end of the string anchor, which is represented with the literal dollar sign "$".The "^" symbol acts as an anchor matching the beginning of the string and the "!" negates the match, so that any string URL that does not match the rest of the expression will be rewritten to the other specified rules. Seemod_rewrite regex vocabularyShareFolloweditedMar 23, 2019 at 18:08MiB59622 gold badges1111 silver badges2828 bronze badgesansweredFeb 9, 2010 at 2:47OwenOwen83.7k2121 gold badges122122 silver badges116116 bronze badgesAdd a comment|
I am redirecting all requests like so:RewriteRule ^sitemap.xml$ sitemap.php?/ [QSA,L] # the line below is the one I'm having trouble with RewriteCond %{REQUEST_URI} !^market-reports$ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) /index.php?section=$1 [QSA,L]All my incoming links are meant to go to index.php, as you can see. But now I want to stop one from going there. I've never written my ownRewriteCondbefore, so I'm a little unsure if what I am doing is correct.Basically what I'm trying to say is: "If incoming URL is a file, directory or /market-reports/ do nothing. Otherwise send on the URL to index.php?section="What am I doing wrong? Thanks
Trying to put an exception to RewriteRule in .htaccess
This is what I ended up doing :Options +FollowSymLinks RewriteEngine on RewriteCond %{REQUEST_URI} !(.*)folder RewriteRule ^(.*)$ folder/$1 [L]ShareFollowansweredJul 19, 2012 at 3:29SparkupSparkup3,72422 gold badges3636 silver badges5050 bronze badges21If you have files in directory folder, How to access it? Please give me solution. I tried above code but it allways redirect to the subfolder's index.php page and I'm using Codeigniter inside of the subfolder–Silambarasan RSep 18, 2019 at 13:22@Sparkup - For core php, it is working absolutely fine for me. Thanks a lot for sharing this solution.–IshpreetSep 16, 2020 at 13:09Add a comment|
I'm trying to rewritehttp://www.example.com/directory/folder/*tohttp://www.example.com/directory/*the htaccess file is indirectorythis is my .htaccess file :RewriteEngine on RewriteBase /directory/ RewriteRule ^(.*)$ folder/$1 [L]Any help would be much appreciated.
htaccess rewrite url remove subdirectory
RewriteRule is handled by Apache's mod_rewrite, whileRedirect is handled by mod_alias. No, you don't need both.Your RewriteRule (which uses regex) will not match/here(but will match such paths as/here/foo.html) because it is looking for a slash immediately after. You can make that optional by using a question mark:RewriteRule ^here(/?.*) http://www.there.com$1 [R=301,L]Now that will have the same effect as your Redirect. RewriteCond can be added to exclude certain paths:RewriteCond $0 !/here/stayhere\.htmlNote that some servers do not have mod_rewrite turned on by default. If addingRewriteEngine onto your configuration does not fix the problem and you cannot switch mod_rewrite on, at least mod_alias provides the RedirectMatch directive, which may be good enough:RedirectMatch 301 ^/here(?!/stayhere\.html)(/?.*) http://www.there.com$1ShareFollowansweredNov 29, 2010 at 20:52PleaseStandPleaseStand31.8k66 gold badges6969 silver badges9595 bronze badges22redirect substitutes the match with the target, leaving the other parts intact. RewriteRule actually goes to the target entirely with nothing carried over from the searched portion. Big difference.–ahnbizcadSep 15, 2016 at 19:57Your links don't work anymore.–user31782Dec 31, 2021 at 16:35Add a comment|
I was using something like this...RewriteRule here/(.*) http://www.there.com/$1 [R=301,L]but couldn't get it to workSo I used this...redirect 301 /here http://www.there.comand it worked fine.Can someone explain the difference? Do you need both?Also... how do I exclude paths from the redirect?Like... redirect 301 all...redirect 301 /here http://www.there.combut/here/stayhere.htmlThanks
What's the difference between RewriteRule and redirect 301
<Directory /uploads> Options +Indexes </Directory>ShareFolloweditedMar 1, 2019 at 11:17javier_domenech6,10566 gold badges3737 silver badges5959 bronze badgesansweredApr 10, 2012 at 14:51Explosion PillsExplosion Pills190k5454 gold badges332332 silver badges410410 bronze badges1How to remove .htaccess password protection from a subdirectorystackoverflow.com/a/1431399/3548026–pixelDinoMar 10, 2019 at 10:54Add a comment|
I have an images folder at the following URL.www.mysite.com/uploads/On a different page:www.mysite.com/search.php/I am trying to access the images wherein, with a correct tag link, however I get the :Forbidden You don't have permission to access /uploads/ on this server.So I went and started dabbling with a.htaccessfile, and I have no idea what I am doing ,I tried looking at some documentation but with no luck, I even took an example off another question..Here is how my.htaccessfile looks atm:<FilesMatch "\.(gif|jpe?g|png)$"> Order allow,deny Allow from all </FilesMatch> <Directory /uploads> # All access controls and authentication are disabled # in this directory Satisfy Any Allow from all </Directory>Any ideas on how I can have it allow access to that folder?
.htaccess file to allow access to images folder to view pictures?
addCheckSpelling onto your.htaccessfile of course after enabling the RewriteEngineso the final code will beRewriteEngine on CheckSpelling onI guess it is the best and safest way.dont forget to changeAllowOverride nonetoAllowOverride Allinside yourhttpd.conffile, to allow .htaccess files to work correctly.ShareFolloweditedJun 20, 2020 at 9:12CommunityBot111 silver badgeansweredOct 11, 2013 at 4:43iEmadiEmad62511 gold badge77 silver badges2020 bronze badges76I just get a 500 Internal Server Error on every page whenever I addCheckSpelling on–Michael YaworskiFeb 3, 2014 at 8:59It is working like a charm for me. try to remove everything else inside the .htaccess file other than RewriteEngine On CheckSpelling On and make sure you AllowOverride All inside you httpd.conf file–iEmadFeb 3, 2014 at 15:581I've removed everything else. The only thing I haven't done is the httpd.conf file because I don't know how to access that. I'm on shared hosting with dreamhost. Is there a way to access that file, or do I have to find another way?–Michael YaworskiFeb 3, 2014 at 19:18Well then, try to contact them and see if they allow using .htaccess or not and ask if they have the mod_rewrite loaded or not–iEmadFeb 3, 2014 at 23:433For anyone else seeing this, you need the mod_speling module enabled as well.–Eirik HMay 9, 2015 at 6:40|Show2more comments
I recently switched from IIS to Apache and unfortionately some of my links have capitalization issues. I have seen quite a few people talking about how to rewrite urls to be all lowercase or all uppercase but I need something to just make Apache case insensitive. Is this doable with .htaccess?
How would I make Apache case insensitive using .htaccess?
Problem is in this rule:#Force from http to https RewriteCond %{SERVER_PORT} 80 RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$ RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301]Change this rule to:#Force from http to https RewriteCond %{HTTPS} !on RewriteCond %{HTTP_HOST} =bbb.example.co.uk RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L,NE]You have condition reversed due to use of!at start and have an extra slash at end which will never be matched hence making your condition always return true.Make sure to clear your browser cache before testing this.ShareFolloweditedJun 25, 2021 at 6:49answeredApr 20, 2016 at 15:16anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges0Add a comment|
I am trying to force a subfolder (/bbb/) of my root domain to show always as https. Also my.htaccessfile take care of the extensions of the pages.I have put the.htaccessfile inside my/bbb/folder but I get "Too many redirects" when I try to force to connect to https, without it everything works fine.Whats wrong in my code?Options +FollowSymLinks -MultiViews Options +Indexes AcceptPathInfo Off RewriteEngine on RewriteBase / ErrorDocument 404 https://example.co.uk/404page/404.html #Force from http to https RewriteCond %{SERVER_PORT} 80 RewriteCond %{HTTP_HOST} !^bbb.example.co.uk/$ RewriteRule ^(.*)$ https://bbb.example.co.uk/$1 [R=301] #take off index.html RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{REQUEST_URI} ^(.*/)index\.html$ [NC] RewriteRule . http://www.%{HTTP_HOST}%1 [R=301,NE,L] ## hide .php extension # To externally redirect /dir/foo.php to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] RewriteRule ^ %1 [R,L,NC] ## To internally redirect /dir/foo to /dir/foo.php RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^ %{REQUEST_URI}.php [L] ## hide .html extension # To externally redirect /dir/foo.html to /dir/foo RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.html [NC] RewriteRule ^ %1 [R,L,NC] ## To internally redirect /dir/foo to /dir/foo.html RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^ %{REQUEST_URI}.html [L]
.htaccess - "Too many redirects" when trying to force https
This solution worked fine, best solution ever for me. Paste this code into root htaccess. That's all. Leave all other files as they are<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ ^$1 [N] RewriteCond %{REQUEST_URI} (\.\w+$) [NC] RewriteRule ^(.*)$ public/$1 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ server.php </IfModule>ShareFollowansweredFeb 7, 2020 at 8:02Mohammad H.Mohammad H.87699 silver badges1919 bronze badges72Where did this code originate? (How does this actually solve the OPs specific problems?)–MrWhiteMar 24, 2020 at 0:03Use this for root folder–Mohammad H.Mar 24, 2020 at 15:557Explanation for this solution would be appreciated, specifically parts which point redirection either to public or server -script, but it does seem to work.–JanneNov 18, 2020 at 13:58First goes to public/* and then points to server.php. So no need to include /public/ anywhere else ;)–Mohammad H.Mar 25, 2021 at 18:591Anyway, thank you, it worked for me perfectly. Hope one day to understand the code, but for today, copy paste is ok–Juan JoyaAug 11, 2021 at 4:36|Show2more comments
I've setup a new install of Laravel on my local. It appears there are issues with htaccess or Apache settings. I've researched for a number of hours and tried everything I read.OSX Lion 10.7.5MAMP 3.0.5PHP 5.5.10mod_rewrite is being loaded.My development server works with other sites. This is the first time I am trying Laravel 4.I get a 403 Forbidden on the welcome page which is located at website.dev:8888/Apache gives me this error: Directory index forbidden by Options directiveHere is my .htaccess file content:<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> 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>Here are a few additional actions I've taken:AllowOverride is set to All in httpd.confAdded virtual host code section to httpd-vhosts.confverified that the hosts file contains a line for the site 127.0.0.1 website.devI've also tried various lines in the htaccess which I found in articles and I also restarted apache each time I made changes to the conf files. No routes work. When I go to website.dev:8888/public I get a blank page, no error. If I go to a route I created such as website.dev:8888/users I get a 404 not found error.Thank you for your help!
Laravel htaccess
You need adding this to your.htaccessfile:RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://YOURWEBSITEDOMAIN/$1 [R,L]See this:http://www.inmotionhosting.com/support/website/ssl/how-to-force-https-using-the-htaccess-fileShareFolloweditedDec 14, 2018 at 8:17CommunityBot111 silver badgeansweredMay 16, 2017 at 16:03Mortada JafarMortada Jafar3,59911 gold badge1919 silver badges3434 bronze badges6Where? And Laravel doesn't it need some specific config?–realteboMay 16, 2017 at 21:541With "Where ?" I mean: in which point of my .htaccess? And also, could is it better your code or the one of the answer of Pandhi Bhaumik?–realteboMay 17, 2017 at 10:331@realtebo before last tag it's mean : (</IfModule>) and i used this code for my site–Mortada JafarMay 17, 2017 at 15:26Great answer! sorted me like a charm–Magige DanielApr 16, 2018 at 8:431"before last tag it's mean : (</IfModule>)" - This is incorrect. If you put this rule at the end, "before the last tag", it will only get processed for requests to static resources. Your URLs that get routed through Laravel won't be redirected. This rule needs to go near thetopof the file (logically, after theRewriteEngine Ondirective).–MrWhiteSep 10, 2020 at 12:39|Show1more comment
I'm starting to develop a new big app, and I'm using Laravel this time, and it's the first time.I need to force HTTPS for all pages, it's not important if from code or by .htaccess, but I'm not able to find a simple tutorial.The official docs dosn't speak about this problem.For info, my acutal .htaccess is<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule>My question is specific to Laravel 5, because I ve no idea on where and how modify this .htaccess file. And also I'am asking you if this is the right way for Laravel or if Laravel has something specific to setup to handle HTTPs.So please do not close my question and try to be more adherent to the Laravel specific topic.If you can post a simple way to modify this file AND/OR What to modify in Laravel config to properly handle https.But in short yes, I want to force every call to transit on HTTPS.
Laravel: how to force HTTPS?
Inapplication/config/config.phpchange:$config['index_page'] = 'index.php';to:$config['index_page'] = '';it is a good idea to do apache reload everytime you change an apache config file.sudo /etc/init.d/apache2 reloador:sudo service apache2 reloador:sudo /etc/init.d/httpd reload(or whatever is the equivalent command for your platform)for what it is worth, here is my .htaccessRewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|static|robots\.txt|favicon\.ico|uploads|googlexxxxxxxx\.html|mobile.html) RewriteRule ^(.*)$ index.php/$1 [L]ShareFolloweditedMay 15, 2013 at 4:48answeredMay 15, 2013 at 4:42Kinjal DixitKinjal Dixit7,82722 gold badges6060 silver badges6868 bronze badges5yes i updated that one also.–Suresh KamrushiMay 15, 2013 at 4:42yes restarted my apache number of time. no use.–Suresh KamrushiMay 15, 2013 at 4:46tried with your htaccess file no success. i change "RewriteBase /projectname" as my ci is under this folder.–Suresh KamrushiMay 15, 2013 at 4:51It work like a charm. Thx so much!–Fabio FilaMar 17, 2017 at 21:49RELOAD THE APACHE!!!–Leandro BardelliAug 13, 2018 at 20:13Add a comment|
This question already has answers here:How to remove "index.php" in codeigniter's path(27 answers)Closed10 years ago.I know this question is being ask already, i tried all those but still unable to remove index.php from url. Here are my detailsUbuntu 12.10 PHP : 5.4.6 Mod_rewrite in on CI verson: 2.1.htacess look like:RewriteEngine On RewriteBase /projectname RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]I also look at the below link but no luck..Cannot remove index.php from url CI based siteHow to remove "index.php" in codeigniter's pathMy "/etc/apache2/sites-available/default" is look like this:<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>Any help appreciated!!
How to remove index.php from codeigniter in UBUNTU [duplicate]
After addingAllowOverride Allto the vhost configuration, got it working. Probably the default configuration wasn't allowing the redirects?Here's my final (and working) vhost configuration:DocumentRoot /var/www/sitefolder/public ServerName site.domain.com <Directory /var/www/sitefolder/public> AllowOverride All allow from all Options +Indexes </Directory>ShareFollowansweredMar 31, 2014 at 9:25ProençaProença1,19633 gold badges1313 silver badges1717 bronze badges13Yep. Whats happening here is that theres a .htaccess in /public/ that fixes the urls to hide the index.php. However for this to run it needs AllowOverride All, as .htaccess is about issuing further apache server config not specified in the /etc/apache (or wherever your distro puts it) cluster of configs–ShayneOct 16, 2017 at 9:16Add a comment|
I have a site that is working on the same server in a different url (staging), but now I've deployed the site and the base url ("/") is redirected to the login url (so laravel is sort of working), but then I get a 404 error from apache.If I use sub.domain.com/index.php/route, it works, but if I use sub.domain.com/route redirects to the login route and gives a 404 error.I also changed the routes.php to return the login view in the route "/" and it show the login form correctly.
Laravel redirects to a route but then apache gives 404 error
You should know first that the rewrite conditions only affect the following rewrite rule, an you added your new rule between the rewrite conditions and the rewrite rule, that means they will now affect your new rule only and not the old one (what you have in you code is that the rewrite rules are only executed if the targeted url is not a file or a directory), so if you want your old rule to be still affected by the rewrite condition, you will have to add your new rule before the rewrite conditions.For your issue, I think zessx has answered enough (It is fixed by adding the[L]flag).In the end you should have something like this :<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^p$ index.php?p= [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?s=$1 [L] </IfModule>ShareFolloweditedOct 15, 2019 at 23:36zessx68.4k2828 gold badges136136 silver badges161161 bronze badgesansweredAug 28, 2012 at 9:17Oussama JilalOussama Jilal7,70922 gold badges3131 silver badges5454 bronze badgesAdd a comment|
I have a simple .htaccess file with the contents below.<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?s=$1 [L] </IfModule>I want to add this rule.RewriteRule ^p$ index.php?p=I tried doing this below but it doesn't work. It seems like both rules are being run. I have tried a couple of different flags and again have had no luck. Could someone tell me how to get this working please.<IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^p$ index.php?p= RewriteRule ^(.*)$ index.php?s=$1 [L] </IfModule>
Using multiple rewrite rules?
You could simply add another RewriteCond to check if the host is metrikstudios.comRewriteCond %{HTTP_HOST} ^metrikstudios\.com [NC]and it should look like this:RewriteEngine On RewriteCond %{HTTP_HOST} ^metrikstudios\.com [NC] RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}ShareFolloweditedAug 6, 2012 at 20:48answeredAug 6, 2012 at 20:36FabianFabian3,47544 gold badges3535 silver badges4343 bronze badges0Add a comment|
I currently have 2 domains that access to the same folder on my server: metrikstudios.com and ziced.com.I want the users that enter throughhttp://metrikstudios.com be redirected tohttps://metrikstudios.com and the users that enter throughhttp://ziced.comdon't be redirected tohttps://ziced.com.I currently have this on my .htaccessRewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Thanks
Redirect to HTTPS with .htaccess with a specific domain
Use Rewrite:RewriteEngine on RewriteRule (.*) http://www.newdomain.com/ [R=301,L]ShareFollowansweredJul 15, 2010 at 13:40Sven KoschnickeSven Koschnicke6,60322 gold badges3434 silver badges4949 bronze badges42This takes every request tohttp://www.newdomain.combut does not forward them.–StarxDec 13, 2012 at 23:20Why do you think that? The docs state it quite clearly: "Use of the [R] flag causes a HTTP redirect to be issued to the browser. If a fully-qualified URL is specified (that is, includinghttp://servername/) then a redirect will be issued to that location. Otherwise, the current protocol, servername, and port number will be used to generate the URL sent with the redirect."httpd.apache.org/docs/2.2/rewrite/flags.html#flag_r–Sven KoschnickeDec 14, 2012 at 8:09First of all I tested it and didn't work, then I went on to find out the cause of it because as you said this is a valid rule, but having/$1at the end worked on most of my servers (I haven't tested in all).–StarxDec 14, 2012 at 13:404Adding/$1will add the path of the request to the new domain. That is not what the OP intendet. For seeing what is going on, you can increase theRewriteLogLevel:httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteloglevel–Sven KoschnickeDec 14, 2012 at 14:33Add a comment|
How can I redirect all requests (irrespective of what page is being requested) on sub.domain.com to newdomain.com? Currently I haveRedirect 301 / http://www.newdomain.com/When a requests comes in for domain.com/shop/product the redirect goes to newdomain.com/shop/product while it should just go to newdomain.com
htaccess: redirect all requests to different domain (without query arguments)
For future reference, you may want to try this:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog2/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog2/index.php [L] </IfModule> # END WordPressShareFollowansweredNov 7, 2011 at 20:46Sterling HamiltonSterling Hamilton90388 silver badges1313 bronze badges2Worked for me having a wordpress installation in the root aswell as another in a subdirectory. Simply used your code in the subdirectories htaccess. THANKS!–AndrewCFeb 1, 2013 at 13:50This rule: RewriteRule ewriteRule . /blog2/index.php [L] makes PHP $_SESSION issues - I can't unset selected $_SESSION vars.–uxmalApr 17, 2021 at 21:26Add a comment|
I have a WordPress installation with an.htaccessfile that looks like this:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPressI tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the.htaccessfile.How do I change it so that I can view the subfolder?
Configuring WordPress .htaccess to view subfolders
Thanks to Ahmed forthe link.As a quick point of reference to anyone too lazy to click on it here's the bit I was after...THE_REQUEST The full HTTP request line sent by the browser to the server (e.g., "GET /index.html HTTP/1.1"). This does not include any additional headers sent by the browser. This value has not been unescaped (decoded), unlike most other variables below.REQUEST_URI The path component of the requested URI, such as "/index.html". This notably excludes the query string which is available as as its own variable named QUERY_STRING.REQUEST_FILENAME The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time REQUEST_FILENAME is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI. Depending on the value of AcceptPathInfo, the server may have only used some leading components of the REQUEST_URI to map the request to a file.ShareFollowansweredJun 20, 2013 at 11:21MarkMark1,08611 gold badge99 silver badges1515 bronze badges0Add a comment|
What is returned by %{REQUEST_FILENAME} and %{THE_REQUEST}?I was just checking over our .htaccess file and it dawned on me, I have very little knowledge of this. The code below uses both. It works I just want understand it.#remove / at the end of URL RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)/$ /$1 [L,R=301] #remove /index.php at the end of URL RewriteCond %{THE_REQUEST} ^.*/index.php RewriteRule ^(.*)index.php$ /$1 [R=301,L]Cheers, Mark
What are the .htaccess elements REQUEST_FILENAME and THE_REQUEST?
You will probably need to put the directives in the.htaccessfile in the particular directory.ShareFolloweditedMar 7, 2017 at 6:55Hassaan7,43666 gold badges3131 silver badges5151 bronze badgesansweredOct 20, 2010 at 13:44GumboGumbo649k110110 gold badges784784 silver badges846846 bronze badges16A ha! Yes! This must be the solution, damn my inflexible mind!–DonutReplyOct 20, 2010 at 13:47Add a comment|
I've got this this rule in my htaccess file to force linked files to download rather than open in the browser:<FilesMatch "\.(gif|jpe?g|png)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>Is there a way to alter theRegExpso it only applies to files in a certain directory?Thanks
Set Content-Disposition header to attachment only on files in a certain directory?
The pattern^(.*)$includes also the prefixfolderA. You must specifyfolderAexplicitly in the pattern and capture only the latter part in the RewriteRule. Then you can drop the RewriteCondRewriteEngine on RewriteRule ^/?folderA/(.*)$ /folderB/$1 [R,L]Never test with301enabled, see this answerTips for debugging .htaccess rewrite rulesfor details.ShareFolloweditedAug 30, 2017 at 7:35answeredFeb 15, 2013 at 23:02Olaf DietscheOlaf Dietsche73.1k88 gold badges106106 silver badges203203 bronze badges0Add a comment|
I know this sounds like so many other questions here, but I can't seem to find the answer.Say you are on: www.domain.com/folderA/folder2/folder3/I want that to redirect to: www.domain.com/folderB/folder2/folder3/So the whole structure stays the same.. it just redirects. Now so far I have:RewriteEngine on RewriteCond %{REQUEST_URI} ^/folderA [NC] RewriteRule ^(.*)$ /folderB/$1 [R=301,L]But when I use that, it'll just do www.domain.com/folderB/folderA/folder2/folder3/What am I doing wrong? How do I get rid of that folderA?
.htaccess redirect from one subfolder to other subfolder
Change your code to this:Options -MultiViews RewriteEngine On RewriteBase /Testlaravel/public/ # Redirect Trailing Slashes... RewriteRule ^(.*)/$ $1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]ShareFolloweditedFeb 12, 2014 at 18:02answeredFeb 12, 2014 at 17:45anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges7i try it but now it's redirect tolocalhost/C:/xampp/htdocs/Testlaravel/public/users/login–user3213240Feb 12, 2014 at 17:49ok i added RewriteBase /Testlaravel/public/ and now it work thx :)–user3213240Feb 12, 2014 at 17:531For me, the line:RewriteBase /Testlaravel/worked, as i am not using public folder and got rid of it. Thanks.–shasi kanthSep 11, 2014 at 13:54It's not work for me.http://localhost/newproject/public/login/works fine. Buthttp://localhost/newproject/public/login/will redirect tohttp://localhost/login–kupendraApr 1, 2015 at 7:35@kupendra: Each one's problem is different, this is not answer to your problem. Post a new question and we'll look into that.–anubhavaApr 1, 2015 at 7:37|Show2more comments
When I try thishttp://localhost/Testlaravel/public/users/loginit works. But when I tryhttp://localhost/Testlaravel/public/users/login/it redirects me tohttp://localhost/users/login/Any idea why?This my htaccess file<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> 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>
laravel trailing Slashes redirect to localhost
First:you have a syntax error.[0-9+]is a character class that can match (i) digits in the range0through9, or (ii) a+sign. To use the+as a quantifier (as intended), move the+after the], like so:([0-9]+).Second:You are using$2in your item which is the product name. If you want to use the ID, you have to use$1.Here's what you need to use:RewriteEngine On RewriteRule ^products/([0-9]+)\-([a-z0-9_\-]+)/?$ products.php?product_id=$1 [NC,L,QSA]I added in the product numbers, dash and underscore in case you need it someday.Third:You should be aware ofsql injections, your script is not safe. You can fix this by usingmysql_real_escape_string.ShareFolloweditedJun 21, 2014 at 4:38zx8141.4k99 gold badges9090 silver badges106106 bronze badgesansweredDec 25, 2011 at 16:35Book Of ZeusBook Of Zeus49.7k1818 gold badges174174 silver badges171171 bronze badges0Add a comment|
i want to rewrite a rule for my products.i want to use the id and name in the url separated by a dash like this:123-name means product id = 123 and name = nameso in my php i can get the $_GET[id] and then query my database using this id like this:$sql = "SELECT * from Products Where productid = " . $_GET[id];here's what i have:RewriteEngine On RewriteRule ^products/([0-9+])\-([a-z]+)/?$ products.php?id=$2 [NC,L]but when i put this as url, i get a 404why?
rewrite urls for product name
Here's what you should use:RewriteEngine On RewriteBase / SetEnvIf Host ^www\. lang=en SetEnvIf Host ^en\. lang=en SetEnvIf Host ^fr\. lang=fr RewriteCond %{REQUEST_URI} !\.(css|png|gif|jpe?g|js)$ [NC] RewriteRule ^([a-z0-9_\-]+)/?$ index.php?lang=%{ENV:lang}&page=$1 [L,NC,QSA]The%{ENV:lang}will be read from theSetEnvIf(from the sub-domain) and set the correct language you will get from$_GET['lang'];(in your PHP code - assuming it's PHP)This way, any of the sub-domain will be dynamically loaded without creating rules over and over for sub-domain. I also added a rule that prevent loading images or JavaScript as page.ShareFollowansweredDec 23, 2011 at 19:29Book Of ZeusBook Of Zeus49.7k1818 gold badges174174 silver badges171171 bronze badges0Add a comment|
i try to look on stackoverflow but i can't find my answer.so i need to find out which domain which sub-domain the user is and which page is loading.eg: en.domain.com/contactusthis should load the english contact us page.what i have is:RewriteCond %{HTTP_HOST} ^(www\.)?domain.com$ [NC] RewriteRule ^(.*)$ index.php?lang=en&page=$1 [L,NC] RewriteCond %{HTTP_HOST} ^en.domain.com$ [NC] RewriteRule ^(.*)$ index.php?lang=en&page=$1 [L,NC] RewriteCond %{HTTP_HOST} ^fr.domain.com$ [NC] RewriteRule ^(.*)$ index.php?lang=fr&page=$1 [L,NC] #etc...but for some reason when i echo the get for page, the value is : index.php so i cannot read the page.
.htaccess page and lang error
In a.htaccessfile, you can use this to define a specific file that will be auto-prepended, in a directory :php_value auto_prepend_file "prepend.php"So, I suppose you could use this to de-activate auto-prepending in a directory :php_value auto_prepend_file noneNote I am using the special value "none", as explained in the documentation ofauto_prepend_file:The special valuenonedisables auto-prepending.ShareFollowansweredNov 24, 2009 at 6:01Pascal MARTINPascal MARTIN398k8080 gold badges659659 silver badges664664 bronze badges1Ha. geez I was using "none" (with quotes) and it wasn't working so I moved on to try other things and eventually post here. That worked perfectly. thx for helping out a n00b!–justinlNov 24, 2009 at 6:03Add a comment|
I'm using auto_prepend on my website, however I don't want it to be used in every folder. How can I stop php from auto_prepending a file within certain folders using .htaccess? (It doesn't have to be .htacces, I can use any other method but I thought I'd start with .htaccess)ps - I'm using the auto_prepend in php.ini to set the auto_prepend
How can I disable auto_prepend in specific folders using htaccess?
No, you can only have one base URL. Just rewrite your rules:RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^blog/. /blog/index.php [L] RewriteCond %{HTTP_HOST} =example.com RewriteCond %{REQUEST_URI} !^/domain RewriteCond %{REQUEST_URI} !^/cgi-bin RewriteRule ^(.*)$ domain/$1 [L]ShareFollowansweredMar 12, 2010 at 18:14GumboGumbo649k110110 gold badges784784 silver badges846846 bronze badges22It seems the lastRewriteBasedirective wins for the entire .htaccess file.–MrWhiteAug 14, 2013 at 19:301In fact, it seems the initial idea behind the use ofRewriteBasein the question is wrong anyway. You would have needed to write theRewriteRulepattern as^blog/.anyway, regardless of the value ofRewriteBase.RewriteBasedoes not affect the URI matched against thepattern, it only affects relativesubstitutions.–MrWhiteAug 14, 2013 at 20:12Add a comment|
I have a domain and a wordpress-blog on same server. Now I have a problem (surprise). The wordpress is located on /httpdocs/blog/ and domain is pointing to /httpdocs/ and I'm trying to redirect it to /httpdocs/domain/. But, obvisiously, I have permalinks in Wordpress.Here's my current .htaccess:RewriteEngine On RewriteBase /blog/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] RewriteBase / RewriteCond %{HTTP_HOST} domain.com RewriteCond %{REQUEST_URI} !^/domain RewriteCond %{REQUEST_URI} !^/cgi-bin RewriteRule ^(.*)$ domain/$1 [L]But as you already propably assumed, this doesn't work. Wordpress' permalinks affects to /domain/ also, so my images and other urls go wrong.Any advice? Is it possible to use RewriteBase like this?
Many RewriteBase in one .htaccess file?
The two rules that you have conflict, the patterns used areexactly the same, which means, other than the conditions which only get applied to the first rule, the two rules are completely indistinguishable.Given this URL:http://www.site.com/blahIs "blah" a page or a user? Can't tell, because the regex pattern (^([a-z0-9]+)$) for both rules matches "blah". So, the first one will always get appliedno matter what. You need to add something to distinguish between the 2, like including a "user" or "page" in the URL:http://www.site.com/user/blah http://www.site.com/page/blehAnd your rules would look like:Options -Indexes RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^user/([a-z0-9]+)$ /profile.php?username=$1 [L] RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^page/([a-z0-9]+)$ /display.php?page=$1 [L]ShareFollowansweredJul 1, 2013 at 20:46Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges1Thank you, it worked for me. I have two seperate pages and I was using same pattern and it was just using only one rewrite rule and I used your solution to distinguish using a prefix. I thought I needed two separate subfolders and separate htaccess for each subfolder which is a headache and didn't work for me due to using a htaccess in website root which was configured to remove php file extension.–mdhzAug 22, 2020 at 15:37Add a comment|
here is my code for .htaccess fileOptions -Indexes RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^([a-z0-9]+)$ /profile.php?username=$1 [L] RewriteRule ^([a-z0-9]+)$ /display.php?page=$1 [L]For the first one it works correctly and is displaying like this:www.site.com/userThe second one is not working, normally is displaying like this www.site.com/display.php?page=10. I want to display the page like this www.site.com/article I tried different things and no result. Please tell me how to make to work with multiple rules. Also please give me an advice on how to use this functionalities in php because I think I done something not really good. My php code for using this rule is:<p><a class="button" href="/<?php echo $user_data['username']; ?>"> Profile</a></p>It works, but maybe is a better way to make a link to take advantage of htaccess.
Multiple htaccess rewrite rule
Give this a shot.<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^folder1(.*)$ http://www.newdomain.com/$1 [L,R=301] </IfModule>ShareFolloweditedAug 17, 2012 at 11:24Alexis Pigeon7,4671111 gold badges4040 silver badges4545 bronze badgesansweredDec 7, 2011 at 13:30brpynebrpyne99699 silver badges1414 bronze badges2Thanks for the code. Your suggestion worked just that we need to replace olddomain with newdomain.–Bijoy ThangarajDec 7, 2011 at 16:38Glad to help! If you could accept the answer I'd appreciate it =)–brpyneDec 7, 2011 at 16:43Add a comment|
I have some files placed under a particular folder in my old domain like this:http://www.olddomain.com/folder1/.I want to redirect all requests that try to access files under this folder to a new domain. Example:http://www.olddomain.com/folder1/page1.html->http://www.newdomain.com/page1.htmlHow do I accomplish this using .htaccess?
.htaccess redirect all pages under a folder to new domain
SetEnvIfNoCase User-Agent .*google.* search_robot SetEnvIfNoCase User-Agent .*yahoo.* search_robot SetEnvIfNoCase User-Agent .*bot.* search_robot SetEnvIfNoCase User-Agent .*ask.* search_robot Order Deny,Allow Deny from All Allow from env=search_robotHtaccess SetEnvIf and SetEnvIfNoCase ExamplesShareFolloweditedDec 26, 2022 at 11:23JoSSte3,14277 gold badges3636 silver badges5656 bronze badgesansweredAug 8, 2012 at 12:46Edward RuchevitsEdward Ruchevits6,5591212 gold badges5353 silver badges8787 bronze badges2I found the code you just posted on SO as well... I just want to allow ONE SPECIFIC user agent rather than trying to block all (I don't want to take a chance on missing one.) Any ideas?–adamdehavenAug 8, 2012 at 12:48Just in case anyone's wondering: yes this also works directly in the apache vhost conf file (on Apache 2.4 at least) - I have "SetEnvIfNoCase ..." before the <Directory> directive and the "Allow from..." inside.–richplaneNov 1, 2016 at 17:38Add a comment|
I have a website I am developing that is also going to be pulled into a web app. I have the following code in my.htaccessfile to prevent access from ANYONE that is not on my allowed IP:Order deny,allow Deny from all AuthName "Restricted Area - Authorization Required" AuthUserFile /home/content/html/.htpasswd AuthType Basic Require valid-user Allow from 12.34.567.89 Satisfy AnyQUESTION: I would like to add anAllow fromrule that will ALSO allow a specific HTTP user agent access to the site.I found this code to redirect if not the user agent:RewriteEngine on RewriteCond %{HTTP_USER_AGENT} !=myuseragent RewriteRule ^files/.*$ / [R=302,L]But I can't seem to figure out how to turn this into anAllow fromrule. Help?UPDATEI found the code below to block specific user agents... I would instead like to say "if NOTmyuseragent, then block."<IfModule mod_rewrite.c> SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT Deny from env=HTTP_SAFE_BADBOT </ifModule>
.htaccess Allow All from Specific User Agent
Add an extra RewriteCond to exclude the conditions that you don't want rewritten. Use a!before the regular expression to indicate that any files matching should fail the condition. The RewriteCond below is untested, but should give you an idea of what you need:RewriteCond %{REQUEST_URI} !\.(jpg|png|css|js|php)$ShareFollowansweredOct 27, 2010 at 22:20DingoDingo3,3451818 silver badges1414 bronze badges5Combine this withallowinga dot in names/routes (so, replacing[^.]with.in the originalRewriteRulefrom your question). A.t.m, you forcefully don't allow a dot there, so of course it's not going to work.–WrikkenOct 27, 2010 at 23:12Ah, you are right Wrikken. Modified the rule and it came together. I really appreciate the help guys–wdavisOct 27, 2010 at 23:24@nbrogi no, as there is the 'end of line' symbol : $ to say it has to end with the extension.–CedricJun 26, 2013 at 1:01note that you should also allow .ico for your favicon and .txt for robots.txt . Si add these rewritecond : RewriteCond %{REQUEST_URI} !/robots.txt$ RewriteCond %{REQUEST_URI} !/favicon.ico$–CedricJun 26, 2013 at 1:12the best think to use here I think is ^(.*)$ instead of ^([^.]+)$–David ConstantineJun 28, 2013 at 22:27Add a comment|
How can I look for an instance for certain file extensions, like .(jpg|png|css|js|php), and if there is NOT a match send it to index.php?route=$1.I would like to be able to allow period's for custom usernames.So, rewritehttp://example.com/my.nameto index.php?route=my.nameCurrent setup:.htaccess:<IfModule mod_rewrite.c> RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^.]+)$ index.php?route=$1 [QSA,L] </IfModule>What works:http://example.com/userpage-> index.php?route=userpagehttp://example.com/userpage/photos-> index.php?route=userpage/photoshttp://example.com/file.js->http://example.com/file.jshttp://example.com/css/file.css->http://example.com/css/file.cssWhat I need to work in addition to above:http://example.com/my.name-> index.php?route=my.name
rewriterule in htaccess to match certain file extensions
You can try using variations ofRewriteMap. You'll need access to the server/vhost config because that directive only works there. You can then use the map inside htaccess files.Say yourblacklist.txtfile looks like this:111.222.33.44 deny 55.66.77.88 deny 192.168.0.1 allowYou can define the map like so:RewriteEngine On RewriteMap access txt:/path/to/blacklist.txtThen in your htaccess, you can invoke the map:RewriteEngine On RewriteCond ${access:%{REMOTE_ADDR}} deny [NC] RewriteRule ^ - [L,F]The condition invokes the map and checks if the remote address maps to the word "deny", and if so, the rewrite rule outright forbids access.If yourblacklist.txtis only a list of IPs, and you don't want to add a "deny" after each one, you'll need to invoke a program map type and write a script, something like this:#!/bin/bash while true do read INPUT MATCH=`grep $INPUT /path/to/blacklist.txt` if [ -z "$MATCH" ]; then echo "allow" else echo "deny" fi donewhich infinite loops read input and greps theblacklist.txtfile. If the IP is in the file, output a "deny", otherwise it outputs a "allow". Then you'd create the map like so:RewriteEngine On RewriteMap access prg:/path/to/blacklist.txtAnd the rewrite rule to check against the map would be no different.ShareFolloweditedJul 7, 2014 at 15:44answeredOct 22, 2012 at 10:12Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges0Add a comment|
Closed.This question isnot about programming or software development. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed1 year ago.The community reviewed whether to reopen this question1 year agoand left it closed:Original close reason(s) were not resolvedImprove this questionI read and understand how to block an ip using htaccess:order deny,allow deny from 111.222.33.44 deny from 55.66.77.88 ... allow from allBut my list of black IPs includes thousands of IPs. I save all IPs to ablacklist.txtfile.Can I use htaccess to callblacklist.txtand block all IPs which are stored in this file? If so, how?
Ban IPs from text file using htaccess [closed]
S3 is a content server andnota web server. You may want to try renting a smallAmazon EC2instance with Apache to do what you want.ShareFollowansweredDec 30, 2012 at 23:45greenimpalagreenimpala3,86633 gold badges3131 silver badges3939 bronze badgesAdd a comment|
I have a site (Made in iWeb) that I am hosting on Amazon S3. I am trying to getwww.domain.com/Apps/Physics.htmlto turn intowww.domain.com/Apps/Physics.I am trying to accomplish this with an .htaccess file. The file is stored in the root of the bucket (where the index.html file is). Here's the problem: It doesn't work. Still can't usewww.domain.com/Apps/Physics.I have a GoDaddy domain, hosted on the S3 server. Does this help?
Amazon S3 and .htaccess
You should be able to put a single check around all your rewrite code.I suspect from your code that the site you are working on will NOT function properly or at all of mod_rewrite is not enabled. In such cases I would omit the checks for mod_rewrite completely and let the webserver fail if it is not enabled.If you should ever end up in a situation where your code is installed on a webserver without mod_rewrite enabled it will be a lot easier to debug and pinpoint the exact problem.ShareFollowansweredJul 14, 2013 at 4:01Michael BanzonMichael Banzon4,92911 gold badge2727 silver badges2828 bronze badgesAdd a comment|
I'm wondering whether I can use RewriteEngine On only once within my htaccess when it is embed in IfModule mod_rewrite.c or do I have to use it every timebecauseit is embeded?See example below. Thanks<ifModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{QUERY_STRING} /?author [NC] RewriteRule .* - [F] </ifModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{QUERY_STRING} g= [NC] RewriteRule ^(.*)$ - [F,L] </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>
RewriteEngine On in <IfModule mod_rewrite.c> every time?
If you have the possibility to edit vhost-configuration file(s) you should always do so. The .htaccess is getting interpreted with every single request which is made to your site while on the other hand the vhost.conf is only interpreted on httpd restart/reload.You could set theOptionsin Directory-directive - e.g.:<Directory /usr/local/apache2/htdocs/somedir> Options +FollowSymLinks +ExecCGI </Directory> <VirtualHost [...]> [...] RewriteEngine On RewriteCond %{SERVER_NAME} ^([^.]+\.[^.]+)$ [NC] RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L] # we check if the .html version is here (caching) RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)$ $1.html [QSA] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f # no, so we redirect to our front web controller RewriteRule ^(.*)$ index.php [QSA,L] </VirtualHost>Also take a look at thiswikiposton apache.org - especially the sectionWhen should I, and should I not use .htaccess files?ShareFolloweditedJun 12, 2014 at 17:30answeredMar 4, 2012 at 13:50SeybsenSeybsen15.3k44 gold badges4242 silver badges7474 bronze badgesAdd a comment|
I was wondering if performance can be increased if I move .htaccess file content into a vhost file of apache2?This is the content of my .htaccessOptions +FollowSymLinks +ExecCGI <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{SERVER_NAME} ^([^.]+\.[^.]+)$ [NC] RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L] # we check if the .html version is here (caching) RewriteRule ^$ index.html [QSA] RewriteRule ^([^.]+)$ $1.html [QSA] RewriteCond %{REQUEST_FILENAME} !-f # no, so we redirect to our front web controller RewriteRule ^(.*)$ index.php [QSA,L] </IfModule>If doing so is a good idea, where in the vhost declaration should I place above content?Thanks!
Move .htaccess content into vhost, for performance
As @jhutar mentioned in comments, similarly in my case as I set up the site on the main domain with trusted SSL certificate the problem disappeared. So, the firebug is showing that error only for self-signed(and/or not-trusted) SSL certificates.ShareFolloweditedJul 3, 2015 at 16:24answeredJun 30, 2015 at 16:17davdav9,0591515 gold badges7878 silver badges142142 bronze badgesAdd a comment|
I am getting this warning in firebug when adding HSTS header.The site specified an invalid Strict-Transport-Security header.here is my htaccess<IfModule mod_headers.c> Header append X-FRAME-OPTIONS: SAMEORIGIN Header append Strict-Transport-Security: 'max-age=31536000; includeSubDomains' </IfModule>When I remove quotes from the value I getInternal Server Error. Website is being served through https, redirect from http to https is set from apache's site file. SSL certificate is self-signed, if it matters.mod headers is enabled. Im on debian 7, apache 2.2.Thanks
The site specified an invalid Strict-Transport-Security header - firebug
If you look at thesource code for mod_rewrite, you'll notice that it sets aproxy-nocanonflag ifnoescapeis enabled.In therevision where that line was first added, it also included this comment:make sure that mod_proxy_http doesn't canonicalize the URI, and preserve any (possibly qsappend'd) query string in the filename for mod_proxy_http:proxy_http_canon()Following on from that, if you read themod_proxy documentation, you'll see the following mention ofnocanon:Normally, mod_proxy will canonicalise ProxyPassed URLs. But this may be incompatible with some backends, particularly those that make use of PATH_INFO. The optional nocanon keyword suppresses this, and passes the URL path "raw" to the backend. Note that may affect the security of your backend, as it removes the normal limited protection against URL-based attacks provided by the proxy.I'm may be mistaken, but that implies to me that the use ofnocanonin mod_proxy (and by extensionnoescapein mod_rewrite) has potential security ramifications. That would explain why it is disabled by default, even thought it seems like it would be more useful to have it enabled in most cases.ShareFollowansweredMay 8, 2013 at 14:24James HoldernessJames Holderness22.9k22 gold badges4141 silver badges5252 bronze badgesAdd a comment|
I've been looking at the[NE](noescape) flag in mod_rewrite. After some thought I couldn't figure out a situation when I wouldNOTwant to use the flag. Meaning, it seems most helpful to keep the flag enabled in almost everyRewriteRule. Not invoking this flag has caused me problems in a few circumstances.Most of the rules that I deal with are HTTP redirects ([R]), rather than passing through.Would someone shed some light as towhen it is helpful to have mod_rewrite encode the URL?Is it generally good practice to enable this flag, or use the default behavior of allowing mod_rewrite escape these special characters? Why?
mod_rewrite NE flag - When is it helpful to encode special chars in the URL?
Add something like this immediately afterRewriteEngine on:RewriteCond %{HTTP_HOST} ^example\.com$ RewriteRule ^(.*) http://www.example.com/$1 [R=301]ShareFollowansweredNov 11, 2010 at 20:47Laurence GonsalvesLaurence Gonsalves140k3535 gold badges251251 silver badges302302 bronze badges2You missed the $ after ^(.*)–Matthew SJan 18, 2014 at 4:351@KnocksX It isn't necessary as*is greedy.–Laurence GonsalvesApr 11, 2014 at 17:05Add a comment|
I would like to modify my .htaccess file so that when someone comes into my site without typing www the site always redirects them to the www version. For example, if my url is www.abc.com and they just type abc.com, I want to redirect them to abc.com.Here is my current htaccess file:<IfModule mod_rewrite.c> RewriteBase / RewriteEngine on RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] </IfModule>Normally I know how to do the redirect, but im having issues since it already has those few lines in there.
how to modify .htaccess file to always redirect to www
This is a more generic solution, because it can be used with any domain name without having to specify the specific domain name in each .htaccess:# Redirect non-www to www: RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]The contrary is also possible (www to non-www):# Redirect www to non-www RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]ShareFollowansweredAug 16, 2012 at 15:05Rodrigo De Almeida SiqueiraRodrigo De Almeida Siqueira1,7631717 silver badges1313 bronze badges22I'm in Magento and this code redirects //mywebsite.com/some/url to //www.mywebsite.com/index.php. Is there an additional step here to keep the URL persisting?–Thomas BennettFeb 6, 2014 at 19:561I think you must remove one "/" from the rule near $1: RewriteRule ^(.*)$%{HTTP_HOST}$1 [R=301,L]–Bahadir TasdemirFeb 2, 2016 at 9:56Add a comment|
I have a website sayhttp://www.example.com/in the root of my website, I have added .htaccess file to redirect any request ofhttp://example.com/tohttp://www.example.com/Recently I have created a new section "Videos" so the URL for videos ishttp://www.example.com/videos/. In this video folder I have another htaccess file which is performing rewriting for video entries. When I am trying to accesshttp://example.com/videos/then its not redirecting me tohttp://www.example.com/videos/I think .htacces is not inheriting the previous rules from the parent directory. Can anyone please tell me what can be the rule I can add in the .htaccess file of /videos/ folder so that any request forhttp://example.com/videos/will be redirected tohttp://www.example.com/videos/URL.
How to redirect non-www to www URL's using htaccess?
I finally found it! Thanks a ton Justin lurman to poiting out the .htaccess file. It made me see that Wordpress didn't have the right to edit my .htaccess file anymore. That was even more weird because I was 100% sure that permissions were good (even way too permissive if you ask me).So I looked into SElinux, as I know it can play tricks on me at times and I was right. Issuing the following command solved it :chcon -R --type=httpd_sys_rw_content_t wp-content/I hope that helps someone else :)ShareFollowansweredAug 7, 2014 at 19:50Alexandre BourlierAlexandre Bourlier4,02244 gold badges4444 silver badges7676 bronze badges31Thanks, it helps on CentOS 7–Libor B.Oct 4, 2016 at 8:261This kicked my butt for a couple hours. Thank you!–thecrazyrussianJun 27, 2018 at 16:04Thanks, it helps on Fedora 36–Anderson KoesterNov 4, 2022 at 22:44Add a comment|
None of my website images are loaded, although paths are correct. In my Apache logs, I have plenty of :(13)Permission denied: [client 87.231.108.18:57108] AH00035: access to my/file/path/some-photo.jpg denied because search permissions are missing on a component of the pathWithinhttpd.conffile :User apache Group apacheAll the way down to my website directory, folders are owned byapache:apache, withchmodset to774all the way down.SELinux booleanhttpd_can_network_connecthas been isOn.I am using a.htaccessfile to redirect my domain name to the appropriate directory. I suspect this might be cause the issue but... this is nothing more than a gut feeling.I do need help, any suggestion is most welcomed. Many thanks!EDITContent of the .htaccess file :RewriteEngine On Options +FollowSymLinks RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L] RewriteCond %{HTTP_HOST} www\.domain\.com RewriteRule (.*) /domain/$1 [L]
Apache - Permissions are missing on a component of the path
No, hashes are never sent to the server, they are in-page fragment identifiers, so only used by the browser. So you're .htaccess would never have access to the hash. You'd have to do some nifty redirects to get that info to your server.Here are some ideas that might spark something:http://forum.modrewrite.com/viewtopic.php?t=3912ShareFollowansweredNov 18, 2011 at 16:01swatkinsswatkins13.6k44 gold badges4949 silver badges7878 bronze badges11You can only redirect from opposite direction, from example.com/teste_page to example.com/#test. Sending a header Location with url that contain a hash work.–jcubicSep 27, 2012 at 15:58Add a comment|
I want to redirect a URL containing a hash to another URL.Example: example.com/#test should redirect to example.com/teste_pageCan this be done using the .htaccess file?
Redirect URL with hash using .htaccess
I think, instead ofRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]you should have something likeRewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]do have the rewrite rule match. Your link is currently produced by the third rule.ShareFolloweditedDec 14, 2011 at 11:32Lightness Races in Orbit382k7777 gold badges653653 silver badges1.1k1.1k bronze badgesansweredDec 14, 2011 at 11:28feeelafeeela29.6k77 gold badges5959 silver badges7171 bronze badgesAdd a comment|
I'm using Codeigniter and followingthese instructionsto force ssl but all requests are being redirected tohttp://staging.example.com/index.php/https:/staging.example.comMy.htaccessis:### Canonicalize codeigniter URLs # Enforce SSL https://www. RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ### # Removes access to the system folder by users. # Additionally this will allow you to create a System.php controller, # previously this would not have been possible. # 'system' can be replaced if you have renamed your system folder. RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [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 index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]
Force https://www. for Codeigniter in htaccess with mod_rewrite
Click on Wamp icon and open Apache/httpd.conf and search "rewrite_module". Remove # as below and save itLoadModule rewrite_module modules/mod_rewrite.soafter that restart all service.ShareFollowansweredJun 18, 2011 at 17:20Sanjeev ChauhanSanjeev Chauhan4,03733 gold badges2424 silver badges3131 bronze badgesAdd a comment|
I have installed WAMP on Windows. I found .htaccess files are not working here. Is there any way to work with .htaccess?
.htaccess not working on WAMP
There are several problems with the .htaccess you have there.As BSen linked in the comment above, you should use FilesMatch. Also, your regular expression is wrong.The problem with the regular expression is that you have an escaped space at the start, so all files must start with a space character (followed by one of config.php, function.php etc)Also a small explaination of the Order allow,deny directive:http://www.maxi-pedia.com/Order+allow+denyTry this:<FilesMatch "config\.php|function\.php|include\.php"> Order allow,deny Deny from all </FilesMatch>If you'd like to deny all but a few files, this would read asOrder deny,allow Deny from all <FilesMatch "index\.php|index\.html"> Allow from all </FilesMatch>ShareFolloweditedMar 4, 2015 at 14:32Maciej Łebkowski3,8472525 silver badges3232 bronze badgesansweredAug 1, 2012 at 12:52Ricky CookRicky Cook95188 silver badges1414 bronze badgesAdd a comment|
This question already has answers here:.htaccess deny access to specific files? more than one(4 answers)Closed9 years ago.I want to deny access to multiple PHP files in directory/all/cstl/.My .htaccess is also stored in this directory.This is my current code and it's not working.<Files "\ (config.php|function.php|include.php)"> Order allow,deny Deny from all </Files>I have tried to deny the directory and allow specific files but it denies the directory and does not allow the requested .php files. My code for this is:<Directory /> Order deny,allow Deny from all <Directory> <Files "index.php|post.php"> Order deny,allow Deny from all </Files>Please give me some example of blocking access to multiple specific files within a directory.
Deny access multiple .php files with .htaccess? [duplicate]
+50The Bad: Apache :-(X-Requested-Within not a standardHTTP Header.You can't read it in apache at all (neither byReWriteCond %{HTTP_X_REQUESTED_WITH}nor by%{HTTP:X-Requested-With}), so its impossible to check it in .htaccess or same place. :-(The Ugly: Script :-(Its just accessible in the script (eg. php), but you said you don't want to include a php file in all of your scripts because of number of files.The Good: auto_prepend_file :-)But ... there's a simple trick to solve it :-)auto_prepend_filespecifies the name of a file that is automatically parsed before the main file. You can use it to include a "checker" script automatically.So create a.htaccessin ajax folderphp_value auto_prepend_file check.phpand createcheck.phpas you want:<? if( !@$_SERVER["HTTP_X_REQUESTED_WITH"] ){ header('HTTP/1.1 403 Forbidden'); exit; } ?>You can customize it as you want.ShareFolloweditedDec 19, 2010 at 16:32answeredDec 19, 2010 at 16:26EhsanEhsan1,94311 gold badge1717 silver badges3030 bronze badgesAdd a comment|
There are some scripts that I use only via ajax and I do not want the user to run these scripts directly from the browser. I use jQuery for making all ajax calls and I keep all of my ajax files in a folder named ajax.So, I was hoping to create an htaccess file which checks for ajax request (HTTP_X_REQUESTED_WITH) and deny all other requests in that folder. (I know that http header can be faked but I can not think of a better solution). I tried this:ReWriteCond %{HTTP_X_REQUESTED_WITH} ^$ReWriteCond %{SERVER_URL} ^/ajax/.php$ReWriteRule ^.*$ - [F]But, it is not working. What I am doing wrong? Is there any other way to achieve similar results. (I do not want to check for the header in every script).
Deny ajax file access using htaccess
Application Load Balancer now supports two new actions: redirect and fixed-response. You can configure these actions as part of the content-based routing rules, enabling you to offload this functionality to the load balancer. This simplifies deployments while benefiting from the scale, the availability, and the reliability of Elastic Load Balancing.Here's what I did to make it work on AWS:Example configuration for ALB redirection - HTTP -> HTTPShttps://aws.amazon.com/about-aws/whats-new/2018/07/elastic-load-balancing-announces-support-for-redirects-and-fixed-responses-for-application-load-balancer/ShareFollowansweredAug 3, 2018 at 9:28bhalothiabhalothia1,3701212 silver badges1515 bronze badges41I am not sure why but this redirect isn't available in dropdown on our newly created ALB.–Pankaj JangidJul 13, 2019 at 8:54@Jangid - Can you share more information, please? Which region? LB type? Creation method? Also, please share a screenshot.–bhalothiaJul 15, 2019 at 10:38I fiddled with it for sometime and the redirect option started to appear. Probably it was some JavaScript cache issue.–Pankaj JangidJul 15, 2019 at 17:46Okay, yeah maybe.–bhalothiaJul 16, 2019 at 10:15Add a comment|
My Apache servers are behind an ALB/ELB. I'm terminating SSL at the load balancer. The load balancer listens on both 80 and 443. I want to redirect all http requests to https.I have this rewrite rule in place in the vhost config:RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]This works, but the issue is that I also have redirects in an htaccess file. When a redirect happens through the htaccess file, it redirects to http first and then the vhost config redirect picks it up and redirects to https. I want to eliminate the extra http redirect.http://mysite.example.com/sub301https://mysite.example.com/sub301http://mysite.example.com/newsub- this redirect is htaccess 301https://mysite.example.com/newsub200I'd like to gracefully get around having the htaccess redirect to http first. I can get around this by addinghttps://%{HTTP:Host} to rewrite rules. Is this the best way to do this:RewriteRule ^sub$ https://%{HTTP:Host}/newsub [R=301,L]
AWS ALB redirect to https
Try this rule:RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ RewriteCond %{HTTPS}s ^on(s)| RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]Here’s an explanation:The first condition tests if the HTTP header fieldHosthas the required format (contains exactly one period).The second condition tests if the concatenated value of the value of theHTTPSvariable (valuesonandoff) ands(so eitheronsoroffs) is equal toonsand captures thes. This means if%{HTTPS}sevaluates toons, the first matching group issand empty otherwise.The rule will match all requests as every string has a start (marked with^) and redirects them to the evaluated value ofhttp%1://www.%{HTTP_HOST}%{REQUEST_URI}if both conditions are true. Where%1is the first matching group of the previous condition (sif HTTPS and empty otherwise),%{HTTP_HOST}is the HTTPHostof the request and%{REQUEST_URI}is the absolute URL path that was requested.ShareFolloweditedJan 6, 2010 at 19:19answeredJan 6, 2010 at 18:14GumboGumbo649k110110 gold badges784784 silver badges846846 bronze badges3Can you also explain this? It's kind of Chinese for me... the first line is for catching only 2-part host (like: example.com). What the second line does, and how?–Yaakov ShohamJan 6, 2010 at 18:17Looks good, but is producing 500 internal error message for me.–TRiGMay 12, 2011 at 9:541On some hosts you will need to replace the second line withRewriteCond %{HTTP:X-Forwarded-SSL}s ^on(s)|for proper SSL detection.–TheoFeb 14, 2015 at 4:01Add a comment|
I'd like to have:http://example.comredirect to:http://www.example.comhttps://example.comredirect to:https://www.example.comAnd anything that ishttp://whatever.example.comNOT append the www likehttp://www.whatever.example.com.
htaccess redirect for non-www both http and https
You can't just escape space like that"\ ". The proper way to do it is"\s".Although I am not sure if putting "\s" in place of space in htaccess file would do the trick. Please let me know if it worked.ShareFolloweditedOct 10, 2012 at 7:42answeredOct 1, 2012 at 9:35user1581900user15819003,69044 gold badges1818 silver badges2121 bronze badges1\sis too broad. it matches any whitespace, not just space.–ahnbizcadSep 15, 2016 at 20:56Add a comment|
I want to redirect from a old url which still appears in the google search to the new one. the old url is this:http://www.marionettecolla.org/file%20_mostra_milano/mostra_marionette-milano.htmand I want to redirect it to the home page:http://www.marionettecolla.org/I used this in my .htaccess:Redirect http://marionettecolla.org/file\ _mostra_milano/mostra_marionette-milano.htm http://marionettecolla.org/but I am getting Error 500... Does anybody know how to solve this problem?
htaccess redirect when there is a space in url
Change the order of the rules. First redirect tohttpsand then let WP take over all of your requests.<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule>ShareFollowansweredOct 3, 2013 at 20:24anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges21I thought it was surely a syntax error in my.htaccessbut sure enough it was WordPress rewrites coming first. Thanks for this!–cfxFeb 14, 2014 at 0:36Thanks for this. Also we should put it in a separate block, outside the wordpress declaration, to prevent wordpress from overriding this rules when we change the permalink settings.–Andrew LiuJul 7, 2016 at 23:48Add a comment|
My Wordpress directory is at www.example.com/blogI recently changed my entire site to force HTTPS. So my .htaccess file in /blog/ looks like this:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule> RewriteEngine on RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}I also changed the site URL in Wordpress settings to be HTTPS.This works perfectly in the homepage, but in any post pages, the end user is able to change to non-secure HTTP, by changing the URL and pressing enter.For example, they can type directly:http://www.example.com/blog/post-1/and it will load as HTTP.What is wrong with my .htaccess file? Where is the loose end?
HTTPS Force Redirect not working in Wordpress
WithApache 2.4, it is easy with<If>/<Else>directives (on%{HTTP_HOST}?).<If "%{HTTP_HOST} == 'foo'"> # configuration for foo </If> <Else> # default configuration </Else>ForApache 2.2and earlier, I would add a parameter to the startup command line of Apache (-Doption) in one of the two environments then test if it is present or not via<IfDefine>.To do this on Windows, with Apache started as a service, modify key registryHKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Apache2.<VERSION>\ImagePathby appending-DFOO. Then, you can write:<IfDefine FOO> # configuration for foo </IfDefine> <IfDefine !FOO> # default configuration </IfDefine>ShareFolloweditedNov 4, 2015 at 1:33Simon E.56.9k1717 gold badges142142 silver badges135135 bronze badgesansweredDec 21, 2012 at 14:56julpjulp3,91011 gold badge2424 silver badges2222 bronze badgesAdd a comment|
I have the following line in my.htaccessfile to select which version of PHP to use:AddType x-httpd-php53 .phpThis works great in the live environment but doesn't apply to the test environment and breaks the site.Is there a way I can put it in an if statement or something by IP of the server or URL of website or something so that it only comes into effect in the live environment?
htaccess if statement
You need to add aRewritecondto prevent it from redirecting when you’re already on the domain that you want. There are loads of examples online if you google it, or see theRewriteCond section of Apache’s mod_rewrite documentation.What you’re looking for is something like:RewriteEngine on Rewritecond %{HTTP_HOST} !^www\.example\.net RewriteRule ^(.*)$ http://www.example.net/$1 [R=301,L]ShareFolloweditedJan 29, 2014 at 19:08TRiG10.3k77 gold badges5858 silver badges111111 bronze badgesansweredJun 16, 2012 at 0:45joshOfAllTradesjoshOfAllTrades1,9821414 silver badges1010 bronze badges0Add a comment|
I have multiple domains on my server. I want to redirect all of them to one (example.net).My .htaccess:RewriteEngine on RewriteRule ^(.*)$ http://www.example.net/$1 [R=301,L]I’m redirecting all URLs on my server to one main domain, but that domain is also redirecting to itself. So www.example.net returns301 Moved Permanentlyand redirects back to itself. I’m told that this isn’t good for SEO. How could I fix this?
In .htaccess, redirect all domains except one
The most efficient way is to white list yourself using the directive designed for that task.Order Allow,Deny Allow from 123.456.789.123Where 123.456.789.123 is your static IP address.When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#orderOr you could do it with mod_rewrite like so.RewriteEngine On RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.123$ RewriteRule .* - [F]Note that 'RewriteEngine On' will be redundant if you already have placed in your rules above this one. So if that's the case you can discard it here.ShareFollowansweredDec 18, 2012 at 17:53MickeyRoushMickeyRoush1,2641010 silver badges44 bronze badgesAdd a comment|
I'm trying to do a quick htaccess to block all but my ip.I have thisorder deny, allow deny from all allow from "MY IP""MY IP" is my ipI can't see if from my ip - is this the correct way to do this ?
.htaccess block all but my ip
Put a .htaccess file in the root folder of your website (where your php script is) and add the following values:php_value upload_max_filesize 100M php_value post_max_size 100M php_value max_execution_time 200 php_value max_input_time 200Of course, you can put other size and time limits. That should work.ShareFolloweditedJan 11, 2012 at 1:08answeredJan 10, 2012 at 23:48Aleksandar VuceticAleksandar Vucetic14.8k99 gold badges5555 silver badges5656 bronze badges6OK, so I did that and set crazy high values to make sure and still no joy. Could it be something else?–TomJan 10, 2012 at 23:56If you are on shared hosting (and you most likely are since you cannot change your php.ini), it might happen that your hosting provider doesn't allow php.ini to be overriden using .htaccess. In that case, just ask them how to do that.–Aleksandar VuceticJan 11, 2012 at 0:24Also, inside your php file, can you put: ini_set('upload_max_filesize', '20M'); etc... just to make sure that you didn't put your .htaccess in the wrong place.–Aleksandar VuceticJan 11, 2012 at 0:28I tried your last suggestion but it would appear I am only allowed to change the max_execution_time using this method.–TomJan 11, 2012 at 11:18Your shared hosting probably doesn't allow any other changes. You should contact them and ask how to do that.–Aleksandar VuceticJan 11, 2012 at 14:55|Show1more comment
I have a page which allows users to upload images.It is returning a 500 error when the user tries to upload larger images though.The following code...<?php echo ini_get("upload_max_filesize"); echo ini_get("post_max_size"); echo ini_get("max_input_time"); echo ini_get("max_execution_time"); ?>...returns:100M 100M 60 3600I'm guessing from this that it's the max-input-time that's causing the problem as i've tested with files under 100mb but taking longer than 60 seconds to upload.I don't have access with my host to the php.ini file, so can I override these settings? I've tried adding an htaccess file but I'm not sure I've put it in the correct place.
Overriding php.ini on server
Take a look at theIndexOptionsdirective in the.htaccessfile. Specifically, the optionNameWidthwhich you can set to either a certain number of characters or make it as wide as it needs to be:IndexOptions NameWidth=40for 40 character width for filename orIndexOptions NameWidth=*for auto width sizing. The options also allows you to set the widths of the other columns.ShareFolloweditedAug 30, 2018 at 21:46MarkHu1,7461616 silver badges3030 bronze badgesansweredApr 12, 2015 at 7:51Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges1N.B.Remember tochmod a+r .htaccessif it is a new file, otherwise the browser won't be allowed to read it. YMMV.–MarkHuAug 30, 2018 at 19:51Add a comment|
When making a directory listing (.htaccess "Options +Indexes"), the default view has very narrow columns.I set up a directory to demonstrate (it will be available for the duration of this question) containing some public domain artwork I made:link. The directory listing in Firefox looks like this:The listing in Chrome, IE, Safari, and Opera looks almost exactly the same. My concern here is that the width of the "Name" column is very narrow, especially in light of having a full HD screen with plenty of horizontal room.The HTML is a simple table, with e.g. the "..>" signifying a longer filename being written explicitly in the HTML proper. So this is being generated by the HTTP server itself, I assume.Is it possible to change this behavior so that file names can be longer? If not, why? If yes, how?
Directory Listing Column Width
HTTP auth will always ask for a username and password, and not just a password. The server doesn't generate the form that pops up, your browser does. And that form will always have a username and password. You can't tell it to only ask for a password.But what you can do is generate an htpasswd file with a blank username so when the login window opens, people only need to enter a password and can leave the username field blank.ShareFollowansweredAug 24, 2012 at 19:30Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges12Is there a way to bypass the dialog box by using the URL? So far providing "empty" username doesn't work when usinghttp://username:password@adress:port.–jeromejFeb 19, 2016 at 17:31Add a comment|
Is it possible to protect a folder with .htaccess by asking just a password?I don't want a username.
.htaccess protect folder without username
Even more such questions could be solved with a link to themanual.If we provide only a link to a generator, the answer has no educational value, and will result only in more trivial questions asked. I'd recommend readinganswers to this question form meta, which contains some relevant discussion.That said, a quickgoogle searchhas returned some useful results:http://www.generateit.net/mod-rewrite/generates rules for/c/d=>index.php?a=b&c=dhttp://tools-for-webmasters.com/mod_rewrite_tool.htmlthis one currently moved tohttps://www.301-redirect.online/htaccess-rewrite-generatorShareFolloweditedJan 30, 2021 at 15:24CommunityBot111 silver badgeansweredSep 12, 2010 at 12:47MewpMewp4,72511 gold badge2121 silver badges2424 bronze badges21+1 both nice! Re the 2nd paragraph: I doubt the influx of trivial questions can be stopped either way. (I have asked a related question onMeta) I'm rather looking for a lazy way to give a useful answer. The manual is too complex for people who know nothing about Apache; your tutorial link looks interesting, though.–PekkaSep 12, 2010 at 13:21@Pekka: There will always be new users who will ask trivial questions, but I think that it's important to teach them to try and learn themselves, so they won't do it again (and become better programmers along the way).–MewpSep 12, 2010 at 13:41Add a comment|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this questionAnybody know an online tool to generate Apachemod_rewriterules to point people with simple .htaccess questions to?I'm thinking of simple standard scenarios:Simple redirects (url1=>url2)Removing / addingwww./a/b/c/dtoindex.php?value1=a&value2=b...and so on and so on....I'm asking because most mod_rewrite questions turning up on SO could be answered with a link to that, and help people help themselves (well, help as far as "help" goes with a generator tool that can be used without actually having to learn how things work.)
Rewrite rule generator? [closed]
+50When Laravel detects a trailing slash, it returns a 301 redirect to an "untrailed slash" version. The redirected request is always 'GET', so you won't be able to get the POST result.The only way to prevent this (assuming you're using Apache) is go to your .htaccess file (should be in the public directory of your laravel installation) and remove the following:# Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301]Now the URLs with trailing slashes won't be redirected anymore.EDIT: If you want to prevent redirects of only certain URIs, instead of removing those lines, you need to specify a stricter condition. For example, to stop redirecting only the links containing "customer", you'll do this:RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !customer RewriteRule ^ %1 [L,R=301]and only the links not containing "customer" anywhere will be redirected.ShareFolloweditedAug 19, 2021 at 14:53answeredAug 19, 2021 at 14:10José A. ZapataJosé A. Zapata1,27711 gold badge77 silver badges1414 bronze badges1Can I check this for a specific route prefix? like if the route hascustomer/and thenuser/registerthen don't check the trailing slash else work as it is.–Muhammad ShareyarAug 19, 2021 at 14:40Add a comment|
There is a problem occurring while using APIs with trailing slash.RouteRoute::post('user/register','UserController@register');It's working fine when I called this routePOSTfrom the postman/website, but I called this route from mobile with a trailing slash like the following.user/register/Laravel, by default, remove the trailing slash but make the request asGETwhen I dump the request method.$method = $_SERVER['REQUEST_METHOD']; $json = json_encode(['response' => $method], true); result -> "{response : 'GET'}"And I am unable to fetch the request body.NOTE: I have tried many solutions but couldn't find any solution, and also, I can't remove or update route calling from the mobile end, so I have to handle it on the server-side.
Laravel 8 misbehaves on trailing slash
You're most likely getting 500 due to looping error.Exclude404.phpfrom last rule as:ErrorDocument 404 /404.php Options -Indexes -MultiViews RewriteEngine on RewriteCond %{THE_REQUEST} \.php [NC] RewriteRule ^(?!404\.php)$ - [L,NC,R=404] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([^/]+)/?(.*)$ ./$1.php [L]ShareFolloweditedDec 24, 2013 at 14:12answeredDec 23, 2013 at 22:34anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges15Yes, this works :) However, when I visit a page that exists e.g.index.php, it loadsindex.phpinstead of404.php. Any idea of how this could be done?–user3130907Dec 23, 2013 at 23:36If a page exists then than that page's .php will be loaded not 404.php. 404.php will be shown only when a page.php doesn't exist.–anubhavaDec 23, 2013 at 23:38Oh. Basically, my intentions are to remove and to prevent the use of.phpin the URL (if the user tries to use/add.phpin the URL, it would result in a 404 error). Could you suggest a method of doing this through htaccess?–user3130907Dec 23, 2013 at 23:52Isn't your rule already doing that? However instead of showing 404 for .php you should show 403 (Forbidden) error which is more common.–anubhavaDec 23, 2013 at 23:56Yes, but if the user tries to access a page that exists e.g.user.php, it will loadusers.phpinstead of loading404.php. It should only loadusers.phpif the request is/users.–user3130907Dec 24, 2013 at 0:03|Show10more comments
I have this .htaccess file:Options -Indexes RewriteEngine on ErrorDocument 404 /404.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^([^/]*)/?(.*)$ ./$1.php RewriteCond %{THE_REQUEST} \.php RewriteRule ^(.*)$ - [L,R=404]However, when I go tolocalhost/example.php, it returns a 500 Internal Server Error.Any help please? Thanks.EDIT:The full error message that comes up is:Not Found The requested URL /example.php was not found on this server. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
500 Internal Server Error when trying to use ErrorDocument to handle request
chmod 755 -R /silex_project/solved my problem. I still don't know why Apache needs write permissions to work.ShareFollowansweredDec 17, 2012 at 20:32OrangeTuxOrangeTux11.3k77 gold badges5151 silver badges7373 bronze badges22this does solve the problem, but does not explain it, see user1428022's anwser–ioleoApr 1, 2014 at 11:502Justchmod 755 .worked for me so problem was with permission for project folder–Luboš RemplíkApr 4, 2014 at 11:24Add a comment|
I'm trying to set up a website using Silex Bootstrap. I've put it in my folder with other web projects and changed the DocumentRoot in the Apache config.<Directory /folder/to/silex_projects/web> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory>But I can't open the index page of the framework, Apache gives:[Mon Dec 17 21:10:52 2012] [crit] [client 127.0.0.1] (13)Permission denied: /folder/to/silex_project/web/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readableI've chmod'ed the whole project folder withchmod a+r -R. Other projects in the same folder are working fine with the.htaccessfile.The.htaccessfile does exist.
Apache error when setting up Silex Bootstrap: unable to check htaccess file
TheRewriteConditions only apply to the next rule. You want this:RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)$ index.php?page=$1 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/([^/]+)$ index.php?page=$1&var=$2ShareFollowansweredMar 30, 2009 at 16:37GregGreg319k5454 gold badges373373 silver badges336336 bronze badges62That's great, after all these years doing mod_rewrites like this it turns out my logic worked by accident... thanks so much–ColinMar 30, 2009 at 17:34awesome, thank you!!.. it's also good to keep in mind that if the file doesn't exists, it will NOT 404, it will just pass it to the next rule.–RobertoJan 30, 2013 at 4:16@Colin - my sentiments exactly. Now I have to figure out whether that's a relief, or a worry...–BenMay 28, 2013 at 8:54@Greg - By using this conditionRewriteRule ^([^/]+)/([^/]+)$ index.php?page=$1&var=$2, The URL remainssame.Please help me on this–AnjaliMar 18, 2015 at 13:48@Roberto, Based on this RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([^/]+)/([^/]+)$ index.php?page=$1&var=$2, The URL remains same. I need to change the URL–AnjaliMar 18, 2015 at 13:51|Show1more comment
I have been using simple mod_rewrite rules for my CMS for years and am now making a new version, I am seeing the rewriteCond not making sense- I have the standard "if is not a file" but I still see the rewriterules being evaluated even though they're not supposed to. My rewrite code:RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)$ index.php?page=$1 RewriteRule ^([^/]+)/([^/]+)$ index.php?page=$1&var=$2I load /page/var and it works fine as index.php?page=page&var=var, but I try to load /css/file.css and it loads index.php?page=css&var=file.css even though /css/file.cssisa file, so the whole rewrite section shouldn't even be evaluated.I've never seen htaccess apparently defy its own logic, can someone help me figure this out? Has anyone ever run across anything like this?
.htaccess !-f rule not working
Make sure AccessFileName set to .htaccessSearch httpd.conf for AccessFileName directive. It defines name of the distributed configuration file:grep -i AccessFileName httpd.confMake sure users are allowed to use .htaccess fileWhat you can put in these files is determined by the AllowOverride directive. This directive specifies, in categories, what directives will be honored if they are found in a .htaccess file. If this directive is set to None, then .htaccess files are completely ignored. In this case, the server will not even attempt to read .htaccess files in the filesystem.grep -i AllowOverride httpd.confWhen this directive is set to All, then any directive which has the .htaccess Context is allowed in .htaccess files:AllowOverride AllSave and close the file. Restart httpd:service httpd restartShareFolloweditedOct 30, 2015 at 4:09Sasidhar Boddeti1,21411 gold badge1111 silver badges2222 bronze badgesansweredJun 17, 2012 at 18:15Unknown3rUnknown3r38611 gold badge44 silver badges55 bronze badges1If you're gettingFailed to restart httpd.service: The name org.freedesktop.PolicyKit1 was not provided by any .service filesthen you need to dosudo httpd restart–MoozeSep 13, 2022 at 1:12Add a comment|
I'm working on a new server and I installed via yum the "Web Server" group. Php and mysql work fine but I can't get .htaccess to work.Heres my test .htaccess file:WASD_TEST_CALL_ERRORI put this as .htaccess in a test folder along with an index.html page. Instead of reporting an error it goes ahead and loads the index page without displaying any errors.Thanks
Centos htaccess not being read
You want to check that HTTPS ison:RewriteEngine On RewriteCond %{HTTPS} on RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]And if it is on (%{HTTPS} on), redirect tohttp://. There is no mod_rewrite variable called%{HTTP}, only%{HTTPS}which can be "on" or "off".The reason why you were getting the too many redirects error is because:RewriteCond %{HTTP} !=onis always true no matter if the request is http or https, since the variable doesn't exist, it willneverbe equal to "on". Therefore, even if the request is http, you keep getting redirected to the same URL (http).ShareFollowansweredOct 7, 2013 at 17:22Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges1Don't know why it is not working for me. I did a simple test like below putting it on the first line of my .htaccess, but still getting alert from browser when I inputhttps://example.comRewriteEngine On RewriteCond %{HTTPS} on RewriteRule .* https://google.com [L]–shenkwenJun 21, 2021 at 15:37Add a comment|
This is the script I have right now, how do I have my script force all traffic to http, currently it is doing the exact opposite, it is forcing all traffic to https.RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]I've also tried this and it didn't workRewriteEngine On RewriteCond %{HTTP} !=on RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]I got this error:Too many redirects occurred trying to open www.blankpage.com .
Forcing http using .htaccess
You could also put a new .htaccess file in the folder you want to ignore, saying:RewriteEngine OffShareFollowansweredDec 19, 2013 at 15:06Albert-Jan VerheesAlbert-Jan Verhees2,10411 gold badge1616 silver badges1919 bronze badges1this one is batter for guys who does not know url rewiting–Rahman QaiserApr 16, 2016 at 11:44Add a comment|
I have a site which uses htaccess in order to use nice URLs. However I want the htaccess file to leave alone a whole folder and it's content completely. The content of my htaccess file is:RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1How should I complete the above code to EXCLUDE completely the folder named "admin"Many thanks in advance!
Exclude folder from htaccess
mod_rewrite doesn't use variables set via SetEnv, instead use this method:#set to 'live' or 'maintenance' RewriteRule .* - [E=STATUS:maintenance] #If the ENVIRONMENT variable is 'maintenance' then show a maintenance page RewriteCond %{REQUEST_URI} !maintenance.html [NC] RewriteCond %{ENV:STATUS} ^maintenance$ RewriteRule ^.*$ /maintenance.html [L]The first line of the bottom three, makes sure that once the user is redirected to the file "maintenance.html", it will not be redirected again. Else the user keeps getting redirected to the same file, causing an 500 internal server error saying "AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error."ShareFolloweditedAug 6, 2013 at 14:29answeredAug 4, 2013 at 20:59JeffreyJeffrey1,77422 gold badges2424 silver badges4444 bronze badges1Thanks Jeffrey. I tried that, but I get a 500 error. I copied what you have exactly, the only difference is my top two lines include: RewriteEngine on Options -Indexes But those lines shouldn't cause that error.–Brandon RohdeAug 5, 2013 at 18:49Add a comment|
I am trying to define an environment variable in my .htaccess file, and then run a rewrite condition using that variable. Below is what I have in my .htaccess file, but the rewrite is not working:RewriteEngine on #set to 'live' or 'maintenance' SetEnv ENVIRONMENT maintenance #If the ENVIRONMENT variable is 'mainetnance' then show a maintenance page to the users RewriteCond %{ENV:ENVIRONMENT} maintenance RewriteRule ^(.*)$ /maintenance.htmlThe purpose of this is to set the site to maintenance mode programmatically by having PHP edit the .htaccess file when it receives a post request from one of GitHub's hooks to pull the repo for an update.
Use RewriteCond based on environment variable in .htaccess
You could try a couple of things (both untested)Redirect "/one two three.exe" http://example.com/one_two_three.exeor useRewriteRuleinstead ofRedirect:RewriteRule /one\ two\ three.exe http://example.com/one_two_three.exeShareFolloweditedMar 29, 2018 at 13:47TylerH21k7070 gold badges7878 silver badges104104 bronze badgesansweredAug 18, 2010 at 17:42KM.KM.1,39122 gold badges2020 silver badges3535 bronze badges11Second one worked for me. I needed to redirect to an URL with a space in it "\ " works perfect!–Gijs PMar 7, 2013 at 16:15Add a comment|
I have a link from anther website that I do not have control ofhttp://example.com/one two three.exeThe correct URL ishttp://example.com/one_two_three.exeNote the underscores instead of spaces.I searched the internet and found this code snippet for .htaccess# Redirect old file path to new file path Redirect /one%20two%20three.exe http://example.com/one_two_three.exeI added this snippet to my preexisting root .htaccess at the top of the file.But it does not seem to work. My browser does not redirect and I get a 404 error page.I believe that it has something to do with the spaces in the original URL but I don't know how to handle spaces in the URL.Suggestions?
.htaccess Redirect on a url with spaces in it
You want to make sure you are redirecting if the actual request is for a php page, and internally rewriting when the URI is missing the php:RewriteEngine On # browser requests PHP RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php RewriteRule ^/?(.*)\.php$ /$1 [L,R=301] # check to see if the request is for a PHP file: RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^/?(.*)$ /$1.php [L]ShareFollowansweredNov 5, 2012 at 3:57Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges81I think thats it. You are the master. Does it make any difference to have the check after the request?–GorrionNov 5, 2012 at 22:23Or would it be better to have the check first and then the browser requests? I guess as it is a 301 yhis will transfer all SEO from mypage.php to the new mypage, right? Thanks again–GorrionNov 5, 2012 at 22:30It doesn't matter what order, they're mutually exclusive.–Jon LinNov 5, 2012 at 22:57If I wanted (as I will be in a few days) also redirect all trafic from http to https what would I be adding to the code? Thank you.–GorrionNov 5, 2012 at 23:082Warning: This looks like the most concise response to this question on SO, but all of the similar answers that I've seen don't account for.phpin the query string (GET /blah?tricked=you.php HTTP/1.1). I believe changing/([^\ ]+)\.phpto/([^?\ ]+)\.phpwould fix it.–stevoSep 14, 2019 at 7:14|Show3more comments
This question already has answers here:Closed11 years ago.Possible Duplicate:Remove .php extension with .htaccessI want to make all my website URLs,myurl/webpageexamples.php, to be renamed to its non-extension versionmyurl/webpageexamples, if possible in.htaccessand at the same time redirect all traffic frommyurl/webpageexamples.phpto the newmyurl/webpageexamples.I have found several to redirect from PHP to non-PHP like:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)\.html$ /$1 [L,R=301]What I have:myurl/webpageexamples.phpWhat I want:myurl/webpageexamplesI would like to have the SEO score transferred to newmyurl/webpageexamples.
Redirect .php URLs to URLs without extension [duplicate]
Well, to my knowledge, the performance difference is negligible, compared to the computing time used for whatever's used in the.htaccess. For what's it's worth, I've seen no measurable difference by having a.htaccessfile.ShareFolloweditedSep 13, 2023 at 5:39kenmistry2,06311 gold badge2121 silver badges3030 bronze badgesansweredJun 9, 2009 at 13:27miklmikl24k2121 gold badges6969 silver badges8989 bronze badges3Of couse, you'd have to set AllowOverrid to None to be able to see the difference.–innaMJun 9, 2009 at 13:32How big a difference? When does that "difference" start to matter?–frio80Jun 9, 2009 at 14:11Well, small enough that I haven't been able to measure the difference. That might not fly in a science paper, but I really don't think there's any performance gain here to speak of.–miklJun 9, 2009 at 15:57Add a comment|
I know this question has been asked many times and I've researched it myself on Google as well but just can't come up with the answer I need.My hosting company is NOT letting me use the httpd config file, instead it wants me to use .htaccess. I am not a server admin but I have to believe that there is a performance hit for using this file? I have a site with approx 5 million page views a month and it's growing. I do not have a lot of rewrite rules just some optimizations we make to serving pages faster ,mod_deflate, caching, etc.Assuming there is a performance hit, my question is, how bad will it be on my site? Can .htaccess handle 5 million page views with some rewrite rules? How would I be able to test this if I wanted to?Thanks.
Apache .htaccess vs httpd - does it really matter?
This.htaccess-file will only allow users to openindex.php. Attempts to access any other files will result in a 403-error.Order deny,allow Deny from all <Files "index.php"> Allow from all </Files>If you also want to use authentication for some of the files, you may simply add the content from your current file at the end of my example.ShareFollowansweredOct 27, 2013 at 20:40AtleAtle1,8771212 silver badges1010 bronze badges41i also want that all js, css files to be visible which are included in index.php–user2897690Oct 31, 2013 at 14:381Try to add something like<Files ~ "\.(js|css)$">Allow from all </Files>–AtleOct 31, 2013 at 17:205how to allow more than 1 file? like index.php and register.php? in<Files "index.php"> Allow from all </Files>–Jeroen van LangenMar 25, 2015 at 21:19This will also allow anyindex.phpin subdirectories. Is there a way to make theAllow from allonly apply to the current directory?–JacobTheDevApr 12, 2019 at 15:37Add a comment|
i have almost 20 pages on server, but i want only a file named abc.php, which users can watch. i want if user forcefully open the other files like //example.com/some.php .htaccess shows 403 error.<Files ~ "^(?!(changepwd|login|register|remind|securitycode|registersuggest)\.php$).*(\.php)$"> AuthName "Reserved Area" AuthType Basic AuthUserFile path_to/.htpasswd AuthGroupFile path_to/.htgroup Order Deny,allow Require group allowed_groups </Files>this is the way i am currently using, but i think there can be more elegant solutions.
Allowing only certain files to view by .htaccess
Use the-lswitch to test for a symbolic linkRewriteEngine On # enable symbolic links Options +FollowSymLinks RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+) index.php [L]Documentationhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.html- ctrl+f for "Treats the TestString as a pathname and tests whether or not it exists, and is a symbolic link."ShareFollowansweredMar 23, 2011 at 23:33JasonJason15.2k1515 gold badges6868 silver badges105105 bronze badgesAdd a comment|
Like a lot of web developers, I like to use .htaccess to direct all traffic to a domain through a single point of entry when the request isn't for a file that exists in the publicly served directory.So something like this:RewriteEngine On # enable symbolic links Options +FollowSymLinks RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+) index.php [L]This means if the request isn't for a css file or an image, my index.php gets the request and I can choose what to do (serve up some content or perhaps a 404)Works great, but I've stumbled upon an issue it can't seem to help me solve.My document root looks like this:asymboliclink -> /somewhere/else css .htaccess img includes index.phpYet, Apache doesn't see the symbolic link to a directory as a directory. It passes the request on to my index.php in the root. I want to serve the link as if it were a folder as it is a link to a folder with it's own index.php. I can accesshttp://example.com/asymboliclink/index.phpby typing it in the address bar of a browser, but I want to be able to access it throughhttp://example.com/asymboliclinkWhat do I need to add to my .htaccess file to make this happen?
.htaccess config with symbolic links and index files not working as expected
If you are using Apache 2.2.16 or later, you can replace rewrite rules entirely with one single directive:FallbackResource /index.phpSeehttps://httpd.apache.org/docs/2.2/mod/mod_dir.html#fallbackresourceBasically, if a request were to cause an error 404, the fallback resource uri will be used to handle the request instead, correctly populating the$_SERVER[‘REQUEST_URI’]variable.ShareFollowansweredDec 8, 2015 at 11:19SirDariusSirDarius42k88 gold badges8787 silver badges102102 bronze badges2This works very well. I'd recommend this.–Joel BodenmannJan 12, 2021 at 16:27@JoelBodenmann yeah it works nice I needed: <Directory /app/public/> DirectoryIndex index.php Options Indexes FollowSymLinks AllowOverride All Require all granted # Rewrite all request from example.com/app to app.example.com FallbackResource /index.php </Directory> <Directory /app/public/bundles/> FallbackResource disabled </Directory> For API platform framework–Daniel SantosJan 20 at 20:48Add a comment|
I have index.php that reads full path by$_SERVER[‘REQUEST_URI’]variable. My task is when user enter:www.domain/resource/777redirect toindex.phpwith path/resource/777and parse$_SERVER[‘REQUEST_URI’]to do some logic. But I have also real files and folders like:css/theme.cssassets/assets.jsresource/locale.jsWhen I try this config:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.php [L]Client could not get all css and etc files. How to write correct rule in Apache to achive this?
Apache redirect all to index.php except for existing files and folders
Thanks for the idea @denoise and @mogosselin. Also with @stslavik for pointing out some of the drawback of my code example.Here's how I do it:Options +FollowSymLinks RewriteEngine On RewriteRule ^user/([0-9]*)/([a-z]*)$ ./index.php?user=$1&action=$2 RewriteRule ^user/([a-z]*)$ ./index.php?user&action=$1by usingvar_dump($_GET);on the linklocalhost/user/1234/updateI gotarray (size=2) 'user' => string '1234' (length=4) 'action' => string 'update' (length=3)whilelocalhost/user/addarray (size=2) 'user' => string '' (length=4) 'action' => string 'update' (length=3)which is my goal. I will just only do other stuffs under the hood with PHP.ShareFollowansweredAug 1, 2014 at 13:47Port 8080Port 808086844 gold badges1212 silver badges2424 bronze badgesAdd a comment|
I have a URLhttp://localhost/index.php?user=1. When I add this.htaccessfileOptions +FollowSymLinks RewriteEngine On RewriteRule ^user/(.*)$ ./index.php?user=$1I will be now allowed to usehttp://localhost/user/1link. But how abouthttp://localhost/index.php?user=1&action=updatehow can I make it intohttp://localhost/user/1/update?Also how can I make this urlhttp://localhost/user/add? Thanks. Sorry I am relatively new to.htaccess.
Pretty URLs with .htaccess
Finally found the answer while working on another site:BeforeFallbackResourcedirective be sure to add aDirectoryIndexdirective with the same file. Haven't had time to research why but it fixed my issue. I blame it on a Chrome bug or possibly Chrome being super picky because no other major browser has an issue.ShareFollowansweredAug 18, 2014 at 6:24BlaineBlaine82922 gold badges99 silver badges1919 bronze badges4Thanks for posting your solution. It was a big help.–MikeFeb 22, 2015 at 4:27So, does anyone know why or how this might work? Is the bad behavior on Apache's side, or is it on Chrome's side?–CharlesMar 17, 2016 at 21:14My guess is that it's bad behaviour on Apache's side but the administrator's fault for configuring the directives wrong. Most likely the other browsers have an issue with it too, but they ignore it whereas Chrome actually says something and breaks.–BlaineJun 14, 2016 at 3:15This worked for me. Thanks because it's been like that for weeks.–John the RipperApr 7, 2017 at 14:08Add a comment|
I have a website on a lamp stack with little to no extra configuration other thanFallbackResource /index.phppresent in my root .htaccessWhen I load the root page (localhost ) in Chrome I receiveGET http://192.168.163.171/ net::ERR_INCOMPLETE_CHUNKED_ENCODING VM110:1in the chrome console after about 10 seconds. If I attempt to follow the link at VM110:1 it takes me to the top of my inline Javascript.More information / What I've triedThis does NOT occur on any other page but rootThere are no 404's in the access log nor any other abnormal codesThere are no errors appearing in the apache error log.The error does not occur in the latest version of IE or Firefox.It caused a problem in both my local environment and hosted. The latter has absolutely no config changes and I expect to be a near default install.When I remove theFallbackResourcedirective my page loads fine without the errorIn index.php the root is treated no different than any other page.This would all be a non-issue because everything loads properly BUT it prevents javascript relying on a finished page load from working.Any further ideas on what is causing the problem or new things I can try? I've considered moving to just using mod_rewrite but this is much simpler.
ERR_INCOMPLETE_CHUNKED_ENCODING Chrome Root page load
Remove extra[OR]and have your code like this:# If the request is not for a valid directory RewriteCond %{REQUEST_FILENAME} !-d # If the request is not for a valid file RewriteCond %{REQUEST_FILENAME} !-f # If the request is not for a valid link RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^project/([^/.]+)/?$ index.php?view=project&project=$1 [L,NC,QSA]ShareFollowansweredApr 5, 2012 at 14:51anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges12To add a little explanation to this: the OR means that if the filename is either "not a file" or "not a directory", since something is neverbotha file and a directory, that will always hold true...–JasperDec 19, 2018 at 22:14Add a comment|
I am trying to adjust my htacess file to skip the rewrite rule if the file or directory exists, but when the file exists, it changes the URL to something different. I don't know why this is happening. Here is my htaccess file:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^project/([^/\.]+)/?$ index.php?view=project&project=$1 [L] RewriteRule ^for/content/ag index.php?view=opening&section=ag [L] RewriteRule ^for/content/bus index.php?view=opening&section=bus [L] RewriteRule ^for/content/fcs index.php?view=opening&section=fcs [L] RewriteRule ^for/content/market index.php?view=opening&section=market [L] RewriteRule ^for/content/trade index.php?view=opening&section=trade [L] RewriteRule ^for/content/teched index.php?view=opening&section=teched [L] RewriteRule ^for/content/([^/\.]+)/?$ index.php?view=content_area&section=$1 [L]The directory /project/nti exists, with an index.php file. When the address mywebsite.com/folder/project/nti is entered, it changes to mywebsite.com/folder/project/nti/?view=project&project=nti. I am applying this on a test server where the sample site is in a subfolder, but when implemented, it will be in the root web server folder.Thanks for any help!
RewriteCond to skip rule if file or directory exists
Try this in your.htaccessfile:# Allow font assets to be used across domains and subdomains <FilesMatch "\.(ttf|otf|eot|woff|woff2)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch>You can read more about this issue in this excellent article I found:https://expressionengine.com/learn/cross-origin-resource-sharing-corsShareFolloweditedJul 4, 2017 at 12:40Elham AM37566 silver badges1515 bronze badgesansweredApr 28, 2017 at 10:02bg17awbg17aw2,89811 gold badge2121 silver badges2727 bronze badges0Add a comment|
I'm having the following error Font from origin 'http://static.example.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access.I am using the following COR setting in .htaccess file here below<IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 month" ExpiresByType text/cache-manifest "access plus 0 seconds" ........ <IfModule mod_headers.c> Header append Cache-Control "public" <FilesMatch "\.(ttf|otf|eot|woff|svg)$"> SetEnvIf Origin "^http://(.*)?example.com$" origin_is=$0 Header set Access-Control-Allow-Origin %{origin_is}e env=origin_is </FilesMatch> <FilesMatch "\.(js|css|xml|gz)$"> Header append Vary: Accept-Encoding </FilesMatch> </IfModule> </IfModule>Please I need help with this
Font from subdomain has been blocked by Cross-Origin Resource Sharing Policy
In your configuration, apache usespublic_htmlas the document rootIf Symfony2 is installed in directory/home/u105859802/public_html/amateur1, the Symfony public directory to serve is/home/u105859802/public_html/amateur1/web/You should useRewriteBase /amateur1/web/But beware, it is not safeYou have to protect your symfony directories! (configuration is accessible)Why don't you try moving your symfony files in your private area ?You can rename the Symfony web directory topublic_htmlSeehow to do that in documentation cookbookSo, my recommendation structure looks like below :/home/u105859802/vendorsrcappbinpublic_html(web by default in symfony2)<- the only public directoryShareFolloweditedSep 23, 2013 at 8:48Touki7,47533 gold badges4141 silver badges6363 bronze badgesansweredFeb 15, 2013 at 10:56julien rollinjulien rollin1,60711 gold badge1212 silver badges1717 bronze badges2Do you mean to move my sf dir to/home/u105859802/amateur1/being a sibling (brother) of/home/u105859802/public_html/And putting into/public_html/dir the contents of my/web/directoy. Thenpublic_html/.htaccessfile should just redirect everything to app withoutRewriteBaseor being justRewriteBase /right ? this wayRewriteRule ^(.*)$ app.php [QSA,L].–JeflopoFeb 15, 2013 at 14:09I can't try it now, let me try it before accepting the answer. Thank you for this useful info !–JeflopoFeb 15, 2013 at 14:18Add a comment|
I want to access my symfony app in production env (http://www.sample.com/amateur1/web/app.php) from this urlhttp://www.sample.com/amateur1.To do that I moved the .htacces file tohttp://www.sample.com/amateur1/.htaccesswith this contents:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /web/ RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ app.php [QSA,L] </IfModule>But when I go tohttp://www.sample.com/amateur1shows a 404 Error, andprod.logisn't written.I also usedRewriteBase /amateur1/web/because I don't know IfRewriteBasepath is relative to theDocumentRootof the server, Or from the path where the.htaccessfile is located. Also tried/amateur1and/amateur1/as RewriteBase due to this answerSymfony2: How to deploy in subdirectory (Apache)With the three try's, The Exceptions page appears unstyled, and not loading any image. But then I get the following error in prod.log file:[2013-02-15 02:06:47] request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /amateur1/" (uncaught exception) at /home/u105859802/public_html/amateur1/app/cache/prod/classes.php line 5121 [] []What I'm doing wrong ?
How to deploy Symfony2 on a shared-hosting?
You would need the rewrite module of Apache:mod_rewrite.Then do something like this:RewriteEngine on RewriteRule ^content/index/(.*)$ $1Here is the official documentation of mod_rewrite:clickShareFollowansweredOct 10, 2011 at 8:51janoliverjanoliver7,7641414 gold badges6161 silver badges103103 bronze badges3I tried it, but it is not working. I am working with CI. Can you suggest some more solutions?–Salman AslamOct 10, 2011 at 8:57I can't test it here right now. mod_rewrite is a pretty popular topic and you will find many information with google. Check if mod_rewrite is enabled and loaded with apache and try to find the correct pattern to work with.–janoliverOct 10, 2011 at 9:04I can confirm that it's working, thanks @janoliver!–eldorjonJun 29, 2023 at 6:19Add a comment|
Currently, I have 20+ URLs on my site in this formathttp://www.example.net/content/index/missionI want to remove /content/index from all URLs, so they should look something like thishttp://www.example.net/missionIn other words, I would always remove /content/index from the URL. I'm sure it's really straightforward, but I'm not very experienced with Apache.
How to remove part of URl with .htaccess?
Try:RewriteEngine On RewriteCond %{HTTP_HOST} ^healthcare\.domain\.com$ [NC] RewriteCond %{REQUEST_URI} !/healthcare/ RewriteRule ^(.*)$ http://staging.domain.com/$1 [L,R]ShareFollowansweredFeb 11, 2014 at 3:14Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges1I had one that was almost identical to yours and it returned the same results - it just gave me staging.domain.com/index.php. I added more information to my question above that may shed more light on why.–OneSolutionStudioFeb 11, 2014 at 13:39Add a comment|
With htaccess I need to redirect all URLs that don't contain a specific URL path (healthcare) to a new domain while keeping the original URL intact.Example:healthcare.domain.com/anydirectory/anything.htmlshould redirect tostaging.domain.com/anydirectory/anything.htmlbut any URL containing /healthcare should not get redirected. As in healthcare.domain.com/industries/healthcare/customers.html should not be redirected.Both domains are on the same server and healthcare.domain.com is pointed to same root as staging.domain.com. They wanted to be able to access the following page staging.domain.com/industries/healthcare/ at healthcare.domain.com. I setup healthcare.domain.com as a new subdomain pointing its root to the same root as staging.domain.com. I then setup a redirect in the htaccess for healthcare.domain.com to redirect to healthcare.domain.com/industries/healthcare which works perfectly, but if you click anywhere else on the site outside of /industries/healthcare/ I need to bring the user back to staging.domain.com/whateverHere is what I have so far:RewriteCond %{HTTP_HOST} ^healthcare\.domain\.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.healthcare\.domain\.com$ RewriteRule ^/?$ "http\:\/\/healthcare\.domain\.com\/industries\/healthcare\/" [R=301,L] RewriteCond %{HTTP_HOST} ^healthcare\.domain\.com$ [NC] RewriteCond %{REQUEST_URI} !/healthcare/ [NC] RewriteRule ^(.*)$ http://staging.domain.com/$1 [L,R=302]But the above always returnshttp://staging.domain.com/index.php
htaccess redirect if the url does not contain a specific directory
The$_SERVER['REQUEST_URI']variable is theentireURI. So if are going tohttp://example.com/example/loginthe$_SERVER['REQUEST_URI']variable is/example/login. Something that you could try doing is changing your htaccess file to:Options +FollowSymLinks RewriteEngine On rewritecond %{REQUEST_URI} !/public/(.*) rewritecond %{REQUEST_URI} !/assets/(.*) RewriteRule ^(.*)$ index.php/$1 [L](Note that^/public/will never match, because theREQUEST_URIwould be/example/public)Then in your code use$_SERVER['PATH_INFO']instead.
I want to change my url. Here I have a directory structure like thishtdocs/ example/ public/ login.php people/ people1.php people2.php animal/ animal1.php animal2.php 404.php assets/ css/ js/then I want the url like below in accordance with the existing directory in the rootlocalhost/example/login localhost/example/people/people1 localhost/example/people/people2 localhost/example/animal/animal1 localhost/example/animal/animal2I've tried making an.htaccessfile with the following contentsOptions +FollowSymLinks RewriteEngine On rewritecond %{REQUEST_URI} !^/public/(.*) rewritecond %{REQUEST_URI} !^/assets/(.*) RewriteRule .* index.php [L]and it's index.php$requested = empty($_SERVER['REQUEST_URI']) ? false : $_SERVER['REQUEST_URI']; switch ( $requested ) { case '/login': include 'public/login.php'; break; default: include 'public/404.php'; }when I headed localhost/example/login, but destination is404.php(ERROR).can you help me?
How rewriting for directory in root directory
RewriteCond %{HTTP_HOST} ^domain.com$ RewriteRule ^(.*) http://www.domain.com/$1 [QSA,L,R=301]It should work, if it dosn't it comes from your DNS, or Vhost configuration.
Ok so I've rewrited URL in my website, now for some reason, it is throwing 404 error if I type www.domain.com, if I type domian.com, everything works fine.DirectoryIndex home.php IndexIgnore * #RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] #RewriteRule ^(.*)$ http://%1/directory/$1 [L,R=301] RewriteRule ^home/?$ home.php [NC] RewriteRule ^about/?$ about.php [NC] RewriteRule ^404/?$ 404.php [NC] ErrorDocument 404 http://domain.com/directory/404Note: I've commented the 1st 2 rewrite rules as even If I change them it doesn't effect after uploading.htaccessto server, feels like it's cached.Additional Info, am using<base>tag which is inembeds.phpif($_SERVER['REMOTE_ADDR'] == '::1') { echo '<base href="http://localhost/projects/directory/" />'; } else { echo '<base href="http://domain.com/directory/" />'; }Directory StructureRoot - home.php about.php -stylesheets default.css -includes embeds.php 404.php .htaccessembeds.phpisincludedinhome.php,about.phpetc, and stylesheets, scripts etc, inshort the head sectionalong with<base>tag are inembeds.php
Rewrite URL www.domain.com causing 404 on my page
things come to mind. I don't think you need to add /blog/ in your permalink structure, (unless wordpress is adding that for you). That should be automatic if that is the file it is installed in.Also, Where is your index.php file for your wordpress install - Is it in the blog folder or in the /public_html/ folder.If you want to display the blog athttp://example.com/blogit should be in the blog folder.What is the filepath you use to log in? Does that work fine?
I have Wordpress installed in a subdirectory:/public_html/blog/I want to be able to access the blog like this:http://example.com/blogand posts like this:http://example.com/blog/category/postnameIn general settings I have the "WordPress Address (URL)" set to:http://example.com/blogPermalinks is set like:/blog/%category%/%postname%In the subdirectory (/public_html/blog/) I have an .htaccess like:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /blog/index.php [L] </IfModule>Everything works EXCEPT for being able to access the blog Home page at:http://www.example.com/blogDoing that sends me to the "Wordpress 404 page not found" page.I'd be very grateful for a solution!EDITI'm an idiot - I missed something vital. I needed to also change the Site URL in Wordpress > General to:http://example.com/blogDoing that and then removing /blog/ from the permalink structure made everything work. I probably wouldn't have spotted this if @IanB hadn't picked up the /blog/ bit not being necessary. Thanks...
Wordpress - Subdirectory - htaccess
you can solve it by redirecting 404 Error to your index.html– In Apache Server hosting, edit Apache configuration:sudo nano /etc/apache2/sites-enabled/000-default.conf– Add ErrorDocument 404 like this: my index.html is found in /var/www/html/vas/index.html– Full file:<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html # redirect 404 to index page ErrorDocument 404 /vas/index.html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>– Restart Apache server by cmd sudo service apache2 restart
I have successfully installed and ran Angular 2 app on my apache server, I am able to navigate through the pages via[routerLink]="['/register']"However when I refresh the page I get a 404 error on the register page. Is there something wrong with my rewrite rules:Options +FollowSymLinks <ifModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !index RewriteRule (.*) index.html [L] </ifModule>Also here is my apache VirtualHost<VirtualHost *:80> ServerName example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/front/dist/browser <Directory /var/www/html/front> AllowOverride All </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
Angular 2 apache .htaccess file 404 on subpages
Check below list,Your site have http link instead of https links, so only you facing the mixed content warning( you can fine this warning in your browser console). Find those links in your website and change those as a https links.Add google API key in configuration.https://developers.google.com/maps/documentation/javascript/get-api-key
I'm using a plugin in WordPress that uses the Google Maps API but keep getting this error:[blocked] Access to geolocation was blocked over secure connection with mixed content to...My site is on SSL, and I've checked that the google API script is not trying to be pulled in via http (it is https as it should be).I'm not sure what could be causing this issue. Maybe there is something I need to do in my htaccess file? Please help! Thanks!
Blocked Access to geolocation was blocked over secure connection with mixed content
After you installed php7.0-cgisudo apt install php7.0-cgi you can add to your .htaccess AddHandler php70-cgi .phptells Apache to run PHP on any file with the extension ".php" using the Module called php70-cgi that is afaik modules/php70-cgi.soA reason why its not working could be the webserver settings in/etc/apache2/sites-available/defaultif there isAllowOverride„None“ set it to „All“ else you can only make setting in<Directory>and not in.htaccess<Directory /var/www/> ... AllowOverride All ... </Directory>
I am using linux server and in my server I have install PHP 7.* version. I want to use PHP code in HTML file. Right now it render PHP code in in web page. I am using the following code in my .htaccess file but it not working.AddHandler x-httpd-php .html .htmandAddHandler php7-script .php .html .htmand<FilesMatch "\.html?$"> SetHandler application/x-httpd-php7 </FilesMatch>But all are these not working.
How to use PHP7 code in HTML file with the help of .htaccess setting
+25We had the same problem with one of our web applications. We solved it by making some of the following changes. It involves making changes in both the frontend and the backend.The first problem in this case is, angular uses/#/as the separator to determine routes and history. If you share a link that has the#char, anything after it will be ignored and not be sent to the server. To dynamically generate metadata for social sites, we need the part after#. So, we eliminate the/#/altogether.angular.module('myApp', []) .config(function($locationProvider) { $locationProvider.html5Mode(true); // });Ref:https://docs.angularjs.org/api/ng/provider/$locationProviderSetting this will make sure your URLs will now change fromhttp://app_host/#/my_urltohttp://app_host/my_urlJust to make sure AngularJS now understands how to interpret its routes, you need to set the base path for your application<html> <head> <base href="/"> </head> </html>With this config, your sharable links now will land on your backend server, where you always return the same index.html file, but with dynamic meta tags based on the extra path params you receive.
I have an AngularJS application that is served up usinghttp-serverI want my the meta-tags (og:title,og:description,og:image) to be populated dynamically forFacebookand other scrapers (like Slack) to post rich-links on social media sites. However, it is tricky because those scrapers do their scraping of the original HTML page before angular dynamically inserts the proper values. So the scrapers see the placeholder values.One solution to this problem is describedhere. Basically: feed the scraper-bots static HTML with desiredogfields already populated. I would like to do that. But unlike that author, I'm not using apache. Inhttp-serverthere is no .htaccess file that I'm aware of.mI useUI-Routerand$state-providerto handle the URLs provided to my application like this:$stateProvider.state('splash', { url: '/', templateUrl: 'html/splash.html', controller: 'SplashCtrl', data: { meta: { 'title': 'My Title', 'description': 'My Description' } } } );Is there some way I can create a state such that scraper-bots will be sent to a different controller than normal human users using a web-browser? How?
Can I get AngularJS to use different controllers for Facebook OpenGraph scraper?
Thanks for @EdCottrell. I finally found an answer for that.First, I debug to find where thephp.inilocates by create a info.php on the working site.<? php phpinfo(); ?>Then, I find if there is any value onauto_prepend_file =. If yes, delete it.Then I open thesite1.conffile and add theauto_prepend_fileline instead of the one from .htaccess<Directory "/path/to/folder"> php_value auto_prepend_file /absolute/path/to/apache-prepend.php </Directory>After restarting the Apache server, everything works again!sudo systemctl restart apache2
I have two sites on a LAMP stack. One (Site1) uses WordPress with Wordfence, and it works perfectly fine. The second website (Site2) only runs a simple index.php file on it:<?php echo "Testing"; ?>However, it shows HTTP ERROR 500 with the error log as below.[Thu Dec 22 16:23:44.774993 2016] [:error] [pid 56607] [client xxx:27253] PHP Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0 [Thu Dec 22 16:23:44.775042 2016] [:error] [pid 56607] [client xxx:27253] PHP Fatal error: Unknown: Failed opening required '/var/www/site1/public_html/public/wordfence-waf.php' (include_path='.:/usr/share/php') in Unknown on line 0Site1 and Site2 have nothing to do with each other, and they are located in separate folders. I am not sure what's happening. Please advise..htaccessfile on Site1# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # Wordfence WAF <IfModule mod_php7.c> php_value auto_prepend_file '/var/www/site1/public_html/public/wordfence-waf.php' </IfModule> <Files ".user.ini"> <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Order deny,allow Deny from all </IfModule> </Files> # END Wordfence WAF
How do I resolve "PHP Fatal error: Unknown: Failed opening required"
How can redirectwww.example.com/index.php?tag=1000towww.example.com/1000You can insert this rule just belowRewriteBaseline:RewriteCond %{THE_REQUEST} /(?:index\.php)?\?tag=([^\s&]+) [NC] RewriteRule ^ /%1? [R=302,L,NE]
I have the following URLwww.example.com/index.php?tag= xxxI want to make it like the following using .htaccesswww.example.com/xxxI done it with this code:Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^(.+?)/?$ /index.php?tag=$1 [L,QSA]SO if I input this URL:www.example.com/index.php?tag=1000it be redirect to:www.example.com/?tag=1000if:www.example.com/1000it works!So I have dublicate URL and it's not good for seo.How can redirectwww.example.com/index.php?tag=1000towww.example.com/1000
.htaccess remove index.php and hide parameter key from URLs
Just to clarify, the php page isn't the one sending POST or GET request, it's thebrowser, which means you can't block by IP. So you need to be checking against the referer here. Problem with that is the referer can be easily forged so this is no guarantee that you'll be denying access.You can check the referer using the%{HTTP_REFERER}variable in mod_rewrite and then use theFflag to deny access:RewriteEngine On # if the request's referer isn't from a php page on your site RewriteCond %{HTTP_REFERER} !^https?://your-domain.com/.*\.php # deny access to the list of php files RewriteRule ^(path/to/protected.php|path/another_protected.php|images/protected.png)$ - [L,F]
I want to limit the access for some pages in my web site. I have some BL pages in PHP and I want to limit thier access to only internal access.I mean that I want that these pages will be denied if the user type them in the browser, but will be accessible if another PHP page will call them (with POST or GET requests).Is it possible to do that in the .htaccess file? If it is, how?
.htaccess deny access from external request
Yes it's possible but you shouldn't use the htaccess digest authentication, you have to implement a custom Login Form in HTML & PHP.You can implement something like this in PHP & htaccessadmin/.htaccess:RewriteCond %{REQUEST_FILENAME} !check_auth.php RewriteCond %{REQUEST_FILENAME} -f RewriteRule .* check_auth.php?file=$0 [QSA,L] # pass everything thru phpadmin/check_auth.php:$file = $_GET['file']; if($_SESSION['user_authenticated']) { // please mind you need to add extra security checks here (see comments below) readfile($file); // if it's php include it. you may need to extend this code }else{ // bad auth error }you can access directory files like thischeck_auth.php?file=filename
I'm working on a site with a directory that is protected with htaccess. I'd like to create a custom login page instead of relying on the browser default. Anyone have any experience with this?I want to connect via a HTML form. Anyone think is it possible?Thanks.
Custom Login with htaccess through HTML/PHP
Have this rule in yourDOCUMENT_ROOT/.htaccess:RewriteEngine On RewriteRule ^$ /wordpress/ [L,R=301]
When I use the following url "http://www.tuto3d.netai.net/wordpress/" in my navigator I access normally my wordpress site but when I usehttp://www.tuto3d.netai.net/I get the index of folder instead and a link to wordpress folder. I want to redirect in my .htaccess thehttp://www.tuto3d.netai.net/to the "http://www.tuto3d.netai.net/wordpress/"and this is my my .htaccess# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /wordpress/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wordpress/index.php [L] </IfModule> # END WordPressThank you in advance
Index of folder in wordpress .htaccess
You can handle the request using one rewriterule.RewriteRule ^item(?:\.php)/([0-9]+)/([^/]+)?/?([^/]+)?/?$ item.php?action=item&id=$1&desc=$2&page=$3 [L]Please note I have added(?:\.php)before^item, just to be sure this rewriterule works, if your webserver for some reason convert requestdomain.com/item/...intodomain.com/item.php/...Tip: you can see your current rewriterule behavior enabling RewriteLog:RewriteLogLevel 9 RewriteLog "/var/log/apache2/dummy-host.example.com-rewrite_log"Be careful do not use this in production.
Ok so i have a url likedomain.com/item/item_id/item_description/pagewhen i type the link without/pageon the url it throws a 404 error and i have to type the trailing slash on the url to make it work..this is my htaccess codeOptions +FollowSymLinks RewriteEngine On RewriteRule ^item/([0-9]+)/(.*)/(.*)/?$ item.php?action=item&id=$1&desc=$2&page=$3i have found this after searching:# add trailing slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^.*[^/]$ /$0/ [L,R=301]which kinda solves my problem but how can i make the trailing slash to be optional by the user if the user wants to add it or not so it wont redirect everytime a slash is not found
apache RewriteRule requires trailing slash at the end of url to work
You can do it by pretending rewrite rules through filter, based on user country ISO code. Please find code below.function prepend_default_rewrite_rules( $rules ) { // Prepare for new rules $new_rules = []; // Set up languages, except default one, get user language code $user = get_current_user_id(); $language_slugs = (array) get_user_meta($user->ID, 'country_code'); // Generate language slug regex $languages_slug = '(?:' . implode( '/|', $language_slugs ) . '/)?'; // Set up the list of rules that don't need to be prefixed $whitelist = [ '^wp-json/?$', '^wp-json/(.*)?', '^index.php/wp-json/?$', '^index.php/wp-json/(.*)?' ]; // Set up the new rule for home page $new_rules['(?:' . implode( '/|', $language_slugs ) . ')/?$'] = 'index.php'; // Loop through old rules and modify them foreach ( $rules as $key => $rule ) { // Re-add those whitelisted rules without modification if ( in_array( $key, $whitelist ) ) { $new_rules[ $key ] = $rule; // Update rules starting with ^ symbol } elseif ( substr( $key, 0, 1 ) === '^' ) { $new_rules[ $languages_slug . substr( $key, 1 ) ] = $rule; // Update other rules } else { $new_rules[ $languages_slug . $key ] = $rule; } } // Return out new rules return $new_rules; } add_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' );
I know this question has been asked so many times but I didn't find any working solution or example which I can use to fix my problem.I have been working on a client site. There are two similar sites, one for their own country and second for other country's visitors.Their main site hosted in the root of the server and second site hosted in the subfolder.Now what I want is a dynamic URL rewrite for the second site which is hosted into a subfolder with the country code of the visiting user.For e.g.http://example.comhttp://example.com/subfolder/are the URLs.I want thishttp://example.com/subfolder/to be changed into thishttp://example.com/country_code/wherecountry_codeis visitor country code in ISO format getting through PHP function.So if the user is fromUnited Statesthesubfoldermust be changed intous, the new URL should be nowhttp://example.com/us/.I want this to work for all types of pages, whether its a page, post, category, tag or author page.So again,http://example.com/subfolder/any-type-of-url/=>http://example.com/country_code/any-type-of-url/Remembercountry_codeis user/visitor country code in ISO format.Let me know if someone needs more information on this. Thanks in Advance.PS: I tried to achieve this usingadd_rewrite_rule()function available in WP.
Rewrite sub folder dynamically with country code in WordPress using PHP
Try this and let me know if it works for you (updated),RewriteEngine On RewriteCond %{THE_REQUEST} ^GET\ /film-al-cinema\/\?titolo=([^\s&]+)&id=([^\s&]+) [NC] RewriteRule ^film-al-cinema\/$ /film-al-cinema/%1/%2? [R,L] RewriteRule ^film-al-cinema/([^/]+)/([^/]+)/?$ /film-al-cinema/?titolo=$1&id=$2 [NC,L]You should create a backup of your current .htaccess file and then use this code. If everything works fine addR=301in place ofRin the last line
I have a problem with my.htaccessrewrite rule (I'm new at this, so probably it's an easy thing)I have a URL that is:http://www.example.com/film-al-cinema/?titolo=Ghost+in+the+Shell&id=315837So I have the title of the movie inside the first variabletitolo=""and the ID of the movie in the second variableid="".I want the URL to look likehttp://www.example.com/film-al-cinema/Ghost+in+the+Shell/315837I've tried to change the htaccess file with this:<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^film-al-cinema/(.*)/([0-9]+)$ film-al-cinema/?titolo=$1&id=$2 [R] </IfModule>but this redirects me to a 404 pageEDITI'm working on Wordpress so the/film-al-cinema/is a Wordpress PageEDIT 2# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^film-al-cinema/([^/]+)/(\d+)/?$ /index.php?page_id=21016&titolo=$1&id=$2 [L] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
.htaccess rewrite url with two variables
Wordpress canonical URL functionality is designed to do this.Although this plugin is not actively supported anymore, it just might work.<?php /* Plugin Name: Disable Canonical URL Redirects Plugin URI: http://www.ImagineThought.com/ Description: Disables the "Canonical URL Redirect" feature of WordPress (in versions of Wordpress 2.3 and greater). To use this plugin, simply activate it. Then, disable this if you need to re-enable the "Canonical URL Redirect" feature of WordPress. Version: 1.0.11.0228 Author: Geoffrey Griffith Author URI: http://www.ImagineThought.com/ License: GPL */ remove_filter('template_redirect', 'redirect_canonical'); ?>
The below .htaccess configuration is not working on Wordpress site to achieve domain redirection with masking:DirectoryIndex index.php Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(www\.)?redir2$ [NC] RewriteRule ^ http://redir1%{REQUEST_URI} [L,NE,P]This is .htaccess ofredir2for redirecting toredir1with masking. The goal is to have user type in for exampleredir2/sub, served content ofredir1/sub, but shown url ofredir2/sub.It is working fine on my local installation. But on my shared hosting it redirects without masking. I assume problem might be somewhere in server configuration.Any ideas what could be the problem?Just for records here is another similar question I asked when I had problem with index file when redirecting with masking:htaccess redirect with domain masking not working when requesting root directory
htaccess redirect with domain masking for Wordpress site not working
You need not add[QSA]to your rewrite rule to force htaccess to encode query string too.http://httpd.apache.org/docs/current/en/mod/mod_rewrite.html
I have a problem concerning .htaccess and QUERY_STRING.I try redirecting an URL with my htaccess that looks like this:http://mydomain.tld/out/http%3A%2F%2Fotherdomain.tld%3Fparam%3D0tohttp://otherdomain.tld?param=0I use RewriteCond and RewriteRule with the REQUEST_URI to redirect the url and everything works fine since REQUEST_URI is urldecoded by default in the htaccess.However, when I email the link to Hotmail, Hotmail urldecodes the slashes and the question mark. The result looks like this:http://mydomain.tld/out/http%3A//Fotherdomain.tld?param%3D0So htaccess takes the link and tries to redirect it but due to the question mark the htaccess "thinks" everything behind the question mark is a QUERY_STRING.The problem: apache2 doesn't urldecode the QUERY_STRING. So what happens is that htaccess redirects tohttp://otherdomain.tld?param%3D0which will fail.So my question is:How can I tell htaccess to either urldecode the QUERY_STRING or use the full requested url (either urlendcoded or urldecoded) including the part after the question markThanks in advance!Cheers
htaccess QUERY_STRING urldecode
I dont know how to allow the access onhttp://www.example.com/adminbut you can avoid that the directory gets called by redirecting the access to the index.php as you can see here:RewriteRule ^admin$ admin/index.phpor if you need get parametersRewriteRule ^admin\/?\?([^#]*)$ admin/index.php?$1
I've been fiddling with this all morning, I really hope someone can help me out. I have a directory on my website which only the admins must be able to access. So I password protected it using a .htaccess file. But I want the index.php to remain accessible.So I tried:AuthUserFile "/home/example.com/passwords/.htpasswd" AuthType Basic AuthName "Admin" require valid-user <FilesMatch "^index\.php$"> Satisfy Any Allow from all </FilesMatch>And yes it works, but only if you explicitly specify index.php in the URL:http://www.example.com/admin/index.php-> OKhttp://www.example.com/admin/-> Popup crying about loginhttp://www.example.com/admin-> Popup crying about loginSo I went on and modified the regular expression:<FilesMatch "^(|index\.php)$"> Satisfy Any Allow from all </FilesMatch>Not the best regular expression I ever wrote but hey there's some result:http://www.example.com/admin/index.php-> OKhttp://www.example.com/admin/-> OKhttp://www.example.com/admin-> Popup crying about loginI just don't see why this doesn't work. I also tried reversing the whole thing like this:AuthUserFile "/home/example.com/passwords/.htpasswd" AuthType Basic AuthName "Admin" <FilesMatch "^(?!index\.php).+$"> require valid-user </FilesMatch>But yet again to no avail... Anyone sees a solution?
Only allow access to directory index
AFAIK RewriteRule must know the precise format of the incoming request URL. Therefore, having an arbitrary number of %252F strings in there isn't supported.What you can do though is have a custom 404 page that parses the request URL for %252F. The custom 404 page would follow the following logic:Search the request URL for %252F If found, replace it with a / (or nothing, up to you) and return a 301 header and an appropriate error page. Else return a 404 header and appropriate error page.That should give you the effect you want. Don't worry about the extra slashes, apache ignores them.
I want to "catch" incoming URLs that enter my server with extra "%252F" characters in the URL (due to some historical reasons) and redirect them (301) to the same url without these characters. For example: incoming url: www.sample.com/content/%252F/foo after .htaccess rule: www.sample.com/content/fooI have to be able to catch several instances of these characters in the url (in the same place), like : www.sample.com/content/%252F/%252F/%252F/foo and remove them all.Which .htaccess RewriteRule should I use?
How can I remove percent encoded slashes using .htaccess rule?
For those using apache. You will need toEnsure you have .htaccess in root path of the site you are hosting. Example /var/wwwUpdate the /etc/apache2/sites-available/defaultFrom<Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory>To<Directory /var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory>Hope this helps someone
I've been searching for hours but haven't found anything that seems to be able to solves this issue.Here's the scenario:I'm making a wp theme based on the "Twenty Eleven" theme. Everything went fine til I decided to change the urls to permalinks. The only page being displayed is the static page that I have defined earlier.I have set up the htacces file. In fact, WP did it automatically. Everything works if I switch back to the default setting, but, for SEO, I would rather use the permalinks option.Here is my htaccess file (it is on my WP installation folder):# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /mysite/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /mysite/index.php [L] </IfModule> # END WordPressI have seen this postwordpress .htaccess with permalinksbut nothing there could help me. Any help would be very nice.UPDATE :Things I have tried already:Delete pages and create again.Access the permalink field on wp_options (db) and setting the value to blank and set the permalink option in the admin again.I´m running it on windows 7 through an apache2 installation of Zend Server.I thought it was a problem related to my localhost environment, so I put the site online. No luck at all. I'm assuming that wordpress can´t change permalinks to a more friendly url type when you set a static front page. What a shame.
Permalinks in Wordpress - Page not found