Chip Bergh is not an “apparel guy,” he says, while walking through Levi’s Stadium in Santa Clara, Calif., the new home of the San Francisco 49ers. The president and CEO of one of the most recognizable clothing companies in the world, Bergh still tries hard to look the part. In the 80-degree July heat, the lanky chief executive is wearing head-to-toe Levi’s: a $750 pair of custom jeans, a crisp, long-sleeved white Western shirt, and a gold trucker jacket embossed with a 49ers chest patch. Bergh, who was named chief of San Francisco–based Levi Strauss & Co. in 2011, even matches the football stadium that surrounds him. Levi’s famous red tab label, visible on every piece of his clothing, is just one Pantone shade away from the 49ers logo. “Most guys are colorblind anyway,” he says with a grin.

Despite the setting, Bergh isn’t really a “sports guy” either. He is much more of a company man. “I still bleed Procter & Gamble blue,” he says about his former employer. But his lack of athletic spirit hardly matters, at least in the room where he’s standing now—the stadium’s 501 Club—which feels more like an homage to Levi and its century-long history than part of a football arena. The walls of the club, named after one of the brand’s first cuts of jean and an iconic style in the Levi pantheon, are lined—literally—with pants: a 3-D sartorial timeline of denim from the company archive. Bergh walks over to a collage of Polaroid photos of people—or as Levi execs refer to them, “fans”—all sporting their favorite pair of faded blues. The company’s 20-year, $220 million investment in the naming rights for the 49ers stadium is part of a larger push to tap into the nostalgia Bergh believes everyone has for the brand. “When there are 68,000 fans coming through the door with their Levi’s jeans, their 49ers jersey, and their Levi’s trucker jacket, this stadium is going to be amazing,” he says.

A crowd full of fans wearing your clothing is the fantasy of anyone heading an apparel company. But at Levi—the largest jeans company in the world and the undisputed founder of the category—the fantasy has been far from reality for a long time. The creator of the 501 has struggled to keep its brand relevant for what Bergh calls Levi’s “Lost Generation.” For 120 years the term “Levi’s” was synonymous with “blue jeans.” Then came the turn of the 21st century, when a fashion explosion in denim suddenly gave shoppers a range of high-end choices—including brands like 7 For All Mankind (founded in 2000) and True Religion (2002), whose labels sounded more like cults than pants. At the same time, lower-end rivals that had been kicking around for a while (Lee and Wrangler) began nibbling away at market share. Levi got lost in the middle.

With $7.1 billion in 1996 sales, the company used to be bigger than Nike. By 2003, Levi’s revenues had bell-bottomed out to $4.2 billion. Over the next decade, sales rose only barely as the company failed to translate affection for the brand into actual purchases. Levi’s design team was late to key trends, like colored denim for women and more tailored jeans for men. Once in the top quintile of the Fortune 500, Levi dropped off the list in 2012.

That kind of decline would be a challenge for any new CEO, yet Bergh, a 57-year-old vegan and former U.S. Army captain, is bringing a discipline to the company that had been missing for nearly 20 years. He has taken an ax to the company’s inflated cost structure and is convinced that he can make Levi grow again. While still relying heavily on the classic pieces of clothing that are the seam of the denim giant’s business (think the button-fly jean, the white pocket tee, the trucker jacket), Bergh is now investing in ways that, with luck, will allow the company to be a trendsetter again.

Chip BerghCEO Chip Bergh, above left, in head-to-toe Levi’sPhoto by Winni Wintermeyer for Fortune

For Bergh the strategy is as much about returning to its roots as it is moving forward. “People really tell stories about what they’ve done in their Levi’s,” he says, with glassy-eyed nostalgia. “Some guy in Russia wrote in on LinkedIn today saying he still has his Levi’s from when he was a kid. You talk to anybody, they want this brand to be successful.”

Listen to Bergh for even just a few minutes and it’s clear that he’s not just a sentimentalist—though he is that. He is, perhaps even above all, a “brand guy.” And Chip Bergh knows, in every fiber of his heart, that Levi’s is the ultimate brand.

A 28-year veteran of P&G and the former head of its then $7 billion global male grooming business, Bergh was a key architect in helping the company turn Gillette Fusion into a $2 billion brand. Now Levi, a family-owned company with public bondholders, is betting that Bergh can work the same magic there. While the company has four brands (Levi’s, Dockers, and the budget-conscious Signature and Denizen labels), Levi’s accounts for about 84% of total sales. The company must somehow capture older disaffected shoppers (“fans who love us, but quite frankly left us,” says Levi’s brand president James Curleigh), as well as the lost generation (“fans who don’t really know who we are”). It must also battle a deteriorating retail environment, as both brick-and-mortar traffic and industry-wide denim sales continue to fade.

The twin challenges are so immense that Bergh is hesitant even to claim he’s on the path to achieving it. “This is not a turnaround yet—it is a turnaround in the making,” he told Fortune in an interview this summer. “We’re in the first TV time-out of the first quarter.” A month later Bergh is just as cautious talking about his plan. “That’s what makes me nervous doing this whole interview,” he says. “It is way too early to declare success.”

There are just five Fortune 1,000 apparel companies that have been around since the 19th century. Founded in 1853, Levi Strauss is the oldest. The company’s namesake creator, a Bavarian native, had journeyed to San Francisco in the midst of the Gold Rush and set up a dry goods business. It wasn’t until 20 years later, though, that Strauss and a Latvian émigré named Jacob Davis invented their famously sturdy pant—then called the “XX” and later renamed the 501. Davis came up with the idea of putting metal rivets at points of strain, such as the base of the fly and pocket corners, and Strauss agreed to take a patent out with Davis for the new riveted pantsmaking process.

Levi'sThe Tailor Shop at Levi’s Eureka lab.Photo by Winni Wintermeyer for Fortune

Ask executives and family members how the apparel maker has survived so long, and the response is nearly uniform—and surprising: It has been the company’s focus on things other than profit, they say. Levi Strauss himself was a notable philanthropist. In the 1890s he established scholarships for students at the University of California at Berkeley. Upon his death he donated a portion of his wealth to the Pacific Hebrew Orphan Asylum in San Francisco. And ever since, say insiders, the company has pursued a mission executives call “profits through principles.” Strauss’s great-great-grandnephew Robert “Bob” Haas, who was CEO from 1984 to 1999 and is now chairman emeritus, spearheaded a manufacturing code of conduct for overseas suppliers and became the first Fortune 500 CEO to extend medical benefits to employees’ domestic partners. In the 1980s, Haas was also one of the earliest corporate executives to champion research funding for HIV/AIDS.

To ensure that this high-minded mission continued, Levi—which had been publicly traded from 1971 until 1985—took itself private through a leveraged buyout. The deal was widely lauded, including by Fortune. But somewhere along the way, the company’s focus on the greater good wasn’t enough to keep other, more prosaic problems at bay. Levi executives, accustomed to a monopoly on the denim market, hardly noticed when young fashionistas began trading in their Levi’s for cooler jeans. Then came another unforced error—this one, ironically, concerning a financial maneuver that the company had seemed to master only 11 years before: an LBO.

Just as the company was hitting its peak in 1996, for reasons that are still somewhat hazy, CEO Haas embarked on yet another leveraged buyout, consolidating voting rights in a small group of relatives. (In an interview with Fortune, Haas declined to address the issue.) The company repurchased nearly one-third of its shares, taking on $3.3 billion in debt. With its eyes now focused on debt repayment, management all but lost sight of the rapidly changing marketplace and its new competition. Levi’s hold on blue jeans has weakened pretty much ever since. Today the company has a 12.5% slice of the U.S. denim trade, down from 14.4% in 2004. Globally, its share has fallen from 7.2% to 5.3% (see chart below). While Levi still lays claim to more market share than any other company, VF Corp.—which owns Lee, Wrangler, and 7 For All Mankind—is right at its heels, according to data from Euromonitor International.

GLOBAL MARKET SHARE, JEANS COMPANIESChart Source: Euromonitor International

The blame for this slow but steady decline, say current and former executives, as well as industry analysts, comes down to equal parts complacency and arrogance. “If you look at any other design team, they go out in the world, they see trends, and they come back with inspiration,” said one former high-ranking executive. “At Levi, designers sit in the company’s archives and look at old Western shirts and jeans.”

ALSO SEE: A Brief History of Blue Jeans

In 1999, Haas exited the chief executive position to make room for Philip Marineau, a former CEO of PepsiCo North America. (Haas remained chairman.) During Marineau’s seven-year tenure Levi’s financial performance was erratic, and revenues slid. (Marineau says in an email to Fortune that the sales results were “inconsistent” because the company was being turned around. “In a turnaround the process is gain control, stabilize, and then grow,” he writes. “The company was saved from bankruptcy and restored to good health.”) In 2006 came a new CEO—this time a company insider, John Anderson. After five years of what current board chair Stephen Neal describes as “nice, easy management,” Anderson was out.

“We have one of the greatest brands in the world, but I think that there may have been periods where we thought the brand itself could carry us through thick and thin,” says Neal. “There is no question that we got complacent.”

Bergh was in Beijing on a project with P&G when his phone rang. On the other end was a headhunter who had a CEO role in mind. In the previous six months Bergh had gotten a handful of phone calls like this. He never took them seriously. But when the headhunter said the position was the top job at Levi, Bergh couldn’t put down the phone. “I’ll never forget it,” he says. “The words out of my mouth were ‘Oh wow. That could be amazing.’”

Off the top of his head, Bergh figured that Levi was a company with $10 billion in revenue. By September 2011, when Bergh actually stepped into the job, the true sales figure was less than half that. Right from the start, he assessed one critical problem his new company faced. Back in 2009 a team of consultants Levi had brought in had recommended that management grow revenue by no less than 8% a year, akin to some of the apparel company’s largest competitors. To get there, Levi’s execs quickly opened 400 new retail outlets, boosting its store count from 1,900 in 2009 to 2,300 a year later. What little growth in sales the company garnered was more than offset by expenses. As employee headcount ballooned 37%—reaching 16,200 in 2010, up from 11,800 the year before—operating expenses shot up by 15%.

Bergh, a former member of VF’s board, knew Levi didn’t have nearly as wide a brand portfolio as its competitor and could not realistically grow at the same rate. VF, in short, wasn’t just a blue jeans company. It owned brands like North Face and Vans in booming categories like athletic wear. By contrast, roughly 85% of Levi sales came from pants; the denim market, meanwhile, was barely expanding, creeping up just 2% to 3% a year. The consultants’ plan wasn’t working, but Levi kept plowing ahead with the same strategy. “The definition of insanity is doing the same thing over and over again and expecting a different result,” says Bergh. “That’s what we were doing.”

Levi's innovation labBart Sights, head of Levi’s innovation lab, confers with colleaguesPhoto by Winni Wintermeyer

At a Levi leadership meeting in July 2012, Bergh gathered the company’s top executives from around the world to communicate the need for radical change. A longtime fan of Jim Collins, a business academic turned guru, Bergh invited him to come speak to his new team. Collins didn’t do many public speeches, but agreed, he says, because Levi was in a “pivotal time in the company’s history.” His topic? “The 20-Mile March.” It was a business strategy he had outlined in his bestselling 2011 book Great by Choice and discussed with Fortune in an interview at the time. Collins liked to illustrate it with a story about two explorers, leading their teams to the South Pole for the first time in 1911. While one explorer marched his group steadily through bad weather and good, the other pushed his team to the brink of exhaustion when the sun was shining and had them hunker down when storms arose. The first explorer and his team made it to the South Pole; the second died on the way home. The lesson: modest-but-consistent progress is better than the kind that comes in fits and starts.

Bergh wanted Levi to be that first team and listened so intently to the speech that “you could hear a pin drop,” he says. The talk inspired him to define what the company’s 20-Mile March would be. The answer was clear, says Bergh: grow revenues as well as profits, modestly but steadily, year in and year out. “No matter what. No excuses,” said Bergh. “If we want to be a great company, that is what great companies do.”

The first mile of that march had actually begun before Bergh knew where he was heading. The new CEO, weeks into the job, had traveled to Levi offices around the world to interview its top 60 employees for an hour apiece. Bergh asked each of them six questions, of which the answers to two were particularly telling: “What three things have to change at this company?” and “What one thing do you want me to change?” As one executive after another responded to the first, Bergh was disturbed to learn that so much of his senior management team was unaware of how poorly the company was doing. As they answered the second, Bergh discovered that few of his top executives had much incentive to perform—and many of the most talented individuals wanted it; they preferred to work in a meritocracy. The company’s culture had created a blanket of complacency. Bergh’s response was to rebuild his team—before long, nine of his 11 direct reports were gone.

In their stead came some key hires. Chief financial officer Harmit Singh was one of the first. Singh, a former CFO of Hyatt Hotels, could “squeeze blood from a rock and get savings out,” says Bergh. Singh began his tightening with the eventual goal of saving the company $175 million to $200 million a year. Levi is on track to cut nearly 20% of its nonretail and nonmanufacturing employees, roughly 800 positions. The company is also targeting its cumbersome supply chain. From shopping bags to fabrics, Levi has long sourced most of its products regionally rather than get a better price with a global buy. Bergh is changing that: By 2015 the company plans to reduce its global vendor base by about half.

Even the process of getting new apparel designs approved had a seemingly bizarre and inefficient protocol. The company’s so-called innovation center was in Corlu, Turkey—some 6,000 miles from Levi’s design team in San Francisco. Anytime the company wanted to move forward on a new wash or cut of denim, designers would have to hop on a plane to Corlu or the product would have to be shipped to California, creating a logistical (and costly) bottleneck. “We were probably spending more on FedEx than on design,” Bergh jokes. So he brought the center, now grandly named the Eureka Innovation Lab, to a spot a few blocks away from Levi headquarters. That the move also helped improve the collaborative process was not lost on Bergh or his top designers.

Paying down the still-imposing debt load from the last LBO is another priority. When Bergh arrived in 2011, the company had $4.8 billion in sales and nearly $2 billion in debt. By the second quarter of 2014, that debt was down more than $500 million and Levi’s credit rating had improved two notches.

With a better cost structure in place, Bergh turned his attention to what he spent his career doing: building great brands. Bergh points to companies like Burberry and Converse that have struggled in the past and have come back by reminding shoppers of their histories, be they grand or cool. For Levi that means highlighting the company’s position as the inventor of blue jeans and the trucker jacket—something they had failed to do for nearly a generation. In fact, in 2009, Levi’s marketing team decided to downplay that past in favor of a dark and alternative image for the brand. Older, faithful buyers were turned off.

Bergh is now trying to woo them back, in large part with a $100 million marketing campaign dubbed “Live in Levi’s” that conjures up the brand’s heritage as an American classic. “We are a democratic brand,” says Bergh. “It’s multimillionaire Silicon Valley entrepreneurs and schoolteachers and plumbers and cowboys and miners. That’s what this brand is all about.”

And, if all else fails, just give the kids a free concert: Witness the scene from a company-sponsored event in August, when more than 2,000 young music fans—exclusively wearing Levi denim—came to Brooklyn to see alternative-rock bands HAIM and Sleigh Bells. It would have looked to any passerby like the lost generation was back. The rub? The concertgoers had to be wearing Levi clothing to get in.

Beyond such one-off gimmicks, Bergh hired James Curleigh, former CEO of Salomon Sports North America, in 2012 to become Levi’s brand president and lead the company’s renewed focus. Curleigh, a grizzled Canadian whose hairstyle seems to be “I just woke up,” goes by the name “J.C.” and exudes an unkempt cool. Rather than sit in the company vaults for inspiration, he scouted stores and shoppers in Las Vegas, Hong Kong, London, Berlin, and New York in a two-week span this past summer. He is overseeing the rollout of major displays spotlighting the company’s historic 501 jeans in a majority of Levi’s now 2,900 stores globally. With the right nostalgia-driven messaging, Curleigh thinks Levi can be the undisputed Goliath of denim again.

Levi's Innovation LabMelissa Hook, a finishing technician, works with indigo vats at the Levi’s innovation lab.Photo by Winni Wintermeyer for Fortune

A central aspect to reinventing the Levi brand in stores is simplifying the often dreaded process of buying jeans. So Bergh and his team have put a “denim bar” in the heart of most Levi stores: Shoppers sidle up to the bar and a storetender helps them figure out what fit, style, and fabric will wash down well. Levi rolled out the concept with its retail distributors as well, and the idea seems to be working: When J.C. Penney traffic numbers were sliding in 2013, Levi experienced double-digit sales growth in its stores, Bergh says, thanks in large part to the bar design. Levi is currently working to refit Macy’s stores across the U.S. with similar bars.

It’s also emphasizing a concept that feels oh-so-Silicon Valley: “innovation.” Yes, the denim business is a surprisingly fertile ground for high-tech reinvention. At the Eureka lab a team of 30 technicians work on prototypes day in and out, their hands turned indigo from the dye. It has gotten so that the team can turn out roughly 30 prototypes a week, taking a product from idea to design in less than 24 hours. The items that have come out of Eureka run the gamut from an environmentally sustainable pocket tee to tech-advanced women’s denim that fits differently depending on your body shape. In July the team was working on a prototype for denim with a metallic finish built for commuters who bike. While the pants look like an ordinary pair of jeans during the day, their metallic finish lights up when hit with fluorescent light (like that from a car’s headlights) to ensure the biker is seen in the dark. Bergh is into sustainability too: He proudly proclaims that he hasn’t washed his jeans in a year.

There are some notable early signs of Bergh’s success. For the first time in three years, Levi was successful in its 20-Mile March: In 2013, the company raised revenues over the previous year (albeit just slightly) while also growing its profitability; Levi increased shareholder value by more than $1 billion.

Operating margins have improved from 7% in 2012 to 10% in 2013, inching closer to the mid-teens seen at VF. And, well, there is perhaps something to the notion that Americans have a special relationship with the country’s pioneer pantsmaker. “Nobody wants Levi to fail,” says consumer behavior expert and founder of Envirosell Paco Underhill. “All of us have a very sentimental relationship to our favorite pair of Levi’s. We hope the Levi team can reignite that passion so it is not just the nostalgia, but the willingness to actually buy something.”

Despite such encouragement—and Bergh’s aggressive and, frankly, sensible approach—he is correct to say, “This is not a turnaround yet.” From a fashion standpoint, the company continues to miss key trends, like stretchier denim for women, which, Bergh says, hurt the business for the past three quarters.

There are also challenges ahead that may be outside Bergh’s control. Although his connection to the Levi’s brand is tighter than a pair of overdried jeggings, the verdict is still out on whether younger shoppers will ever feel the same way. The chief executive sees that in his own home: When he took the top job at Levi in 2011, neither of his sons (then 24 and 28) had ever owned a pair of the company’s jeans.

As for the denim market overall, that continues on its plodding course. In 2013, U.S. denim sales were up just 2.6%, to $19.1 billion, and Euromonitor predicts that annual growth will slow to as little as 1.2% by 2017. “Denim has been in a downward spiral,” said Macy’s president Jeffrey Gennette in a September investor presentation. In sharp contrast, Barclays estimates the domestic athletic apparel market—think yoga pants and Lycra tops—will increase from $70 billion to $100 billion by 2020. Despite the glaring divergence in growth targets, Bergh appears unfazed. “I am not afraid of yoga pants,” says Bergh. “They are a fad. They are going to come, they are going to go. Blue jeans are going to be around for another 141 years.”

This story is from the October 6, 2014 issue of Fortune.